一道scjp题,请求大家帮忙!
Question 50
Given:
1. public class Plant {
2. private String name;
3. public Plant(String name) { this.name = name; }
4. public String getName() { return name; }
5. }
1. public class Tree extends Plant {
2. public void growFruit() { }
3. public void dropLeaves() { }
4. }
Which is true?
A. The code will compile without changes.
B. The code will compile if public Tree() { Plant(); } is added to the
Tree class.
C. The code will compile if public Plant() { Tree(); } is added to the
Plant class.
D. The code will compile if public Plant() { this(”fern”); } is added to
the Plant class.
E. The code will compile if public Plant() { Plant(”fern”); } is added to
the Plant class.
Answer: D为什么选d呢?
------解决方案--------------------答:这是因为:
public class Tree extends Plant {
public void growFruit() { }
public void dropLeaves() { }
}
在编译时,编程程序自动加上:
public class Tree extends Plant {
public Tree()
{
super();//这是自动调用Plant的无参构造器。而你又没有定义。所以报错。答案d,正是加上这个无参的构造器。
}
public void growFruit() { }
public void dropLeaves() { }
}
------解决方案--------------------对于给出参数的构造函数,最好给出无参的构造函数,否则有子类继承时,在初始化对象时,调用 super();就会找不到默认的无参构造函数!