2 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超7個(gè)贊
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);
}
}
這只是一個(gè)基本準(zhǔn)則,僅供參考。這里的要點(diǎn)是可以在后續(xù)子類(lèi)中覆蓋行為。Java教程

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
請(qǐng)問(wèn)你的行中的fs是什么
Animal p1 = fs.new Liger();
順便說(shuō)一句,看看這段代碼并告訴我它是否符合您的要求。
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
}
添加回答
舉報(bào)