解决方案 »

  1.   

    多态嘛,子类重写了toString()方法啦,走的是子类的方法。话说楼主英语不错啊
      

  2.   

    import java.util.*;class Characteristic
    {
    private String s; Characteristic(String s)
    {
    this.s = s;
    System.out.println("Creating Characteristic " + s);
    }
    }class Description
    {
    private String s; Description(String s)
    {
    this.s = s;
    System.out.println("Creating Description " + s);
    }
    }class Rodent2
    {
    private String name = "Rodent";
    private Characteristic ch = new Characteristic("Has tail");
    private Description d = new Description("Is mammal"); Rodent2()
    {
    System.out.println("Rodent2 construstor");
    } protected void run()
    {
    System.out.println("Rodent2.run()");
    } protected void eat()
    {
    System.out.println("Rodent2 eats");
    } public String toString()
    {
    return name;
    }
    }class Mouse2 extends Rodent2
    {
    private String name = "Mouse";
    private Characteristic ch = new Characteristic("likes cheese");
    private Description d = new Description("afriad cats"); Mouse2()
    {
    System.out.println("Mouse2 constructor");
    } protected void run()
    {
    System.out.println("Mouse2.run()");
    } protected void eat()
    {
    System.out.println("Mouse2 eats");
    } public String toString()
    {
    return name;
    }
    }class Gerbil2 extends Rodent2
    {
    private String name = "Gerbil";
    private Characteristic ch = new Characteristic("is Wild");
    private Description d = new Description("seeking food"); Gerbil2()
    {
    System.out.println("Gerbil2 constructor");
    } protected void run()
    {
    System.out.println("Gerbil2.run()");
    } protected void eat()
    {
    System.out.println("Gerbil2 eats");
    } public String toString()
    {
    return name;
    }
    }class Hamster2 extends Rodent2
    {
    private String name = "Hamster";
    private Characteristic ch = new Characteristic("climb trees");
    private Description d = new Description("like nuts"); Hamster2()
    {
    System.out.println("Hamster2 constructor");
    } protected void run()
    {
    System.out.println("Hamster2.run()");
    } protected void eat()
    {
    System.out.println("Hamster2 eats");
    } public String toString()
    {
    return name;
    }
    }class Randomgen2
    {
    Random rand = new Random(); public Rodent2 next()
    {
    switch (rand.nextInt(3))
    {
    default:
    case 0:
    return new Mouse2();
    case 1:
    return new Gerbil2();
    case 2:
    return new Hamster2();
    }
    }
    }public class RodentEx12
    {
    static Randomgen2 rdg = new Randomgen2(); public static void main(String[] args)
    { Rodent2[] rd = new Rodent2[10];
    for (Rodent2 r : rd)
    {
    r = rdg.next();
    System.out.println(r);
    }
    }
    }你应该把你程序的主要代码给挑出来,这太多太繁琐了;