1、import java.util.*;/(用来随机创建的)抽象基类/PetCreator.javaabstract class PetCreator private Random rand=new Random(47);public abstract Listtypes();public Pet randomPet()int n=rand.nextInt(types().size(); /随机范围arrayList(int size)ArrayListresult=new ArrayList();Collections.addAll(result, createArray(size); Sys
2、tem.out.println(“已填加“ +result.size()+“个种类“);/根据Pet 数组引用 装入容器return result;/PetCreator 的派生类/ForNameCreator.javaclass ForNameCreator extends PetCreatorprivate static Listtypes=new ArrayList();private static StringtypesNames=“typeinfo.pets.Mutt“,“typeinfo.pets.Pug“,“typeinfo.pets.EgyptianMau“,“typeinfo
3、.pets.Manx“,“typeinfo.pets.Cymric“,“typeinfo.pets.Rat“,“typeinfo.pets.Mouse“,“typeinfo.pets.Hamster“, ;private static void Loader()tryfor(String name:typesNames)types.add(Class)Class.forName(name);catch(ClassNotFoundException e)System.out.println(“创建对象的Class类时出现错误“);throw new RuntimeException(e);sta
4、tic System.out.println(“开始向types容器输入各类 Class类型信息“);Loader();public Listtypes()return types;/返回对容器(类型信息类)的引用 typespublic static void main(String arges)new ForNameCreator();/随机创建.javaclass 随机创建 public static voidcountPets(PetCreator creator) /向上转型为抽象基类的引用creator.arrayList(20);/调用基类中arrayList 函数/开始真的随机
5、创建20个宠物对象 并放入容器中public static void main(String arges) /一切从这里开始countPets(new ForNameCreator(); /创建派生类对象 调用本类静态函数/*以下的模块框架是上面的材料*/5层类继承的基类 第一层/Individual.javaclass Individualpublic Individual(String name) this.name=name;protected Individual() String name;/第 2层/Person.javaclass Person extends Individua
6、lpublic Person(String name)super(name);public Person()super();/第 2层 最后大部分都是围绕这个类/Pet.javaclass Pet extends Individualpublic Pet(String name)super(name);public Pet()super();/第 3层/Rodent.javaclass Rodent extends Petpublic Rodent(String name)super(name);public Rodent()super();/第 4层/Hamster.javaclass Ha
7、mster extends Rodentpublic Hamster(String name)super(name);public Hamster()super();/第 4层/Mouse.javaclass Mouse extends Rodentpublic Mouse(String name)super(name);public Mouse()super();/第 4层/Rat.javaclass Rat extends Rodentpublic Rat(String name)super(name);public Rat()super();/第 3层/Dog.javaclass Dog
8、 extends Petpublic Dog(String name)super(name);public Dog()super();/第 4层/Pug.javaclass Pug extends Dogpublic Pug(String name)super(name);public Pug()super();/第 4层/Mutt.javaclass Mutt extends Dogpublic Mutt(String name)super(name);public Mutt()super();/第 3层/Cat.javaclass Cat extends Petpublic Cat(Str
9、ing name)super(name);public Cat()super();/第 4层/EgyptianMau .javaclass EgyptianMau extends Catpublic EgyptianMau(String name)super(name);public EgyptianMau()super();/第 4层/Manx.javaclass Manx extends Catpublic Manx(String name)super(name);public Manx()super();/第 5层/Cymric.javaclass Cymric extends Manxpublic Cymric(String name)super(name);public Cymric()super();public class ceshi/以下代码本人只做了简单修改并加以实现 原作者:Java 编程思想 Bruce Eckel