- Java code
class Animal{//7 Animal(){ System.out.println("Class Animal"); }}class Fish extends Animal{//8 Fish(){ System.out.println("Class Fish"); }}class GoldFish extends Fish{//9 GoldFish(){ System.out.println("Class GoldFish"); }}public class TestInheritanceConstructor extends Animal{//1 private GoldFish goldfish = new GoldFish();//2 public TestInheritanceConstructor(){ //3 System.out.println("TestInheritanceConstructor");//4 } public static void main(String[] args){//5 new TestInheritanceConstructor();//6 }}
------解决方案--------------------
可以把你的代码改一下会看的更加清楚如:
public class testConstructor extends Animal {
private GoldFish goldfish = new GoldFish("1");// 2
public testConstructor() { // 3
super("2");
System.out.println("TestInheritanceConstructor");// 4
}
public static void main(String[] args) {// 5
new testConstructor();// 6
// GoldFish goldfish = new GoldFish();// 2
}
}
class Animal {// 7
Animal(String name) {
System.out.println("Class Animal:" + name);
}
}
class Fish extends Animal {// 8
Fish(String name) {
super(name);
System.out.println("Class Fish:" + name);
}
}
class GoldFish extends Fish {// 9
GoldFish(String name) {
super(name);
System.out.println("Class GoldFish:" + name);
}
}
结果是:
Class Animal:2
Class Animal:1
Class Fish:1
Class GoldFish:1
TestInheritanceConstructor