2 回答
TA贡献1796条经验 获得超7个赞
public abstract class Animal {
private int size;
public Animal() {
size = -1;
}
public Animal(int size) {
this.size = size;
}
public void setSize( int size ) {
this.size = size;
}
public int getSize() {
return size;
}
public static void main(final String[] args) {
Animal[] animals = new Animal[2];
animals[0] = new Liger(20);
animals[1] = new Liger();
for(int i = 0; i < animals.length; ++i) {
System.out.println("Size : " + animals[i].getSize());
}
}
}
public class Tiger extends Animal {
public Tiger() {
super();
}
public Tiger(int size) {
super(size);
}
}
public class Liger extends Animal {
public Liger() {
super();
}
public Liger(int size) {
super(size);
}
}
这只是一个基本准则,仅供参考。这里的要点是可以在后续子类中覆盖行为。Java教程
TA贡献1836条经验 获得超4个赞
请问你的行中的fs是什么
Animal p1 = fs.new Liger();
顺便说一句,看看这段代码并告诉我它是否符合您的要求。
public static void main(final String[] args) {
Animal[] animals = new Animal[10];
Animal p0 = new Liger();
p0.size = 11;
animals[0] = p0;
Animal p1 = new Liger();
animals[1] = p1;
System.out.println("p0.size "+ p0.size); // call as a superclass instance
System.out.println("real p0.size "+ ((p0 instanceof Liger) ? ((Liger)p0).size : ((Tiger)p0).size) ); // cast to call the effective instance of the subclass
System.out.println("p1.size "+ p1.size); // call as a superclass instance
System.out.println("real p1.size "+ ((p1 instanceof Liger) ? ((Liger)p1).size : ((Tiger)p1).size) ); // cast to call the effective instance of the subclass
}
添加回答
举报