管理所有抽象方法
Manage all abstract methods
我创建了一个名为 Creature 的抽象 class 和两个扩展名为 Human 和 Dog 的 Creature 的 classes。还有getAge、setAge等方法,大家可以看到:
public abstract class Creature {
public abstract void born(String name);
public abstract void setName(String name);
public abstract void setAge(int age);
public abstract int getAge();
public abstract String getName();
}
public class Human extends Creature {
private String name;
private int age;
public void born(String name){
setName(name);
setAge(0);
}
// getters and setters
}
public class Dog extends Creature {
private String name;
private int age;
public void born(String name){
setName(name);
setAge(0);
}
// getters and setters
}
然后我做了这个:
private static Creature creature;
String string = new Random().nextInt(2) == 1 ? "Human" : "Dog";
if (string.equals("Human")) {
setCreature(new Human());
} else {
setCreature(new Dog());
}
for (int i = 0; i < 5; i++) {
creature.born("Name" + i);
// here are born 5 creatures
}
// after one year get all creatures and set their age +1
我的问题是,如何让所有生物出生并在一年后将它们的年龄设置为+1?
我假设 setCreature 在一种列表中添加了一个新生物
你只需要遍历列表并增加年龄,而不用关心生物的类型
for(Creature c : creatures){
c.setAge(c.getAge() +1 );
}
我创建了一个名为 Creature 的抽象 class 和两个扩展名为 Human 和 Dog 的 Creature 的 classes。还有getAge、setAge等方法,大家可以看到:
public abstract class Creature {
public abstract void born(String name);
public abstract void setName(String name);
public abstract void setAge(int age);
public abstract int getAge();
public abstract String getName();
}
public class Human extends Creature {
private String name;
private int age;
public void born(String name){
setName(name);
setAge(0);
}
// getters and setters
}
public class Dog extends Creature {
private String name;
private int age;
public void born(String name){
setName(name);
setAge(0);
}
// getters and setters
}
然后我做了这个:
private static Creature creature;
String string = new Random().nextInt(2) == 1 ? "Human" : "Dog";
if (string.equals("Human")) {
setCreature(new Human());
} else {
setCreature(new Dog());
}
for (int i = 0; i < 5; i++) {
creature.born("Name" + i);
// here are born 5 creatures
}
// after one year get all creatures and set their age +1
我的问题是,如何让所有生物出生并在一年后将它们的年龄设置为+1?
我假设 setCreature 在一种列表中添加了一个新生物
你只需要遍历列表并增加年龄,而不用关心生物的类型
for(Creature c : creatures){
c.setAge(c.getAge() +1 );
}