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 t
the Plant class. 
E. The code will compile if public Plant() { Plant(“fern”); } is added t
the Plant class. 
Answer: D
这道题应该先C吧,E选项的话IDE会认为Plant是一个方法也不是一个构造函数。
我这样理解对吗?不对的话,哪儿错了???谢谢。。

解决方案 »

  1.   

    should be D, 自己想吧
      

  2.   


    原因是Tree没有定义构造函数,那么默认是调用父类中无参构造函数进行初始化public Plant() { ... },但是在Plant中只定义了带参数的构造函数。或者还有一种方式就是去掉Plant中的构造函数,那么Plant默认就调用Object(){...}进行初始化,这样就不是出错了
      

  3.   

    父类中 Plant 没有定义无参的构造函数,只有一个有参的构造函数,
    子类 Tree继承Plant 必须也得有个有参的构造函数,而且类型 参数必须和Plant中的构造函数相同
    如果 Plant 中,没有定义构造函数,会默认调用无参的构造函数。
      

  4.   


    正确答案:A. The code will compile without changes. 
    // 错误。Plant类里定义了一个有参的构造Plant(String name),Tree类必须定义一个有参的构造,用来调用Plant类。B. The code will compile if public Tree() { Plant(); } is added to the 
    Tree class.
    // 错误。Plant类定义了一个有参构造方法,系统就不会生成默认Plant()构造方法了。所以调用肯定出问题。C. The code will compile if public Plant() { Tree(); } is added to the 
    Plant class. 
    // 正确。由于方法可以重载,构造方法也不例外,因此,当然可以再定义一个Plant()的构造方法。D. The code will compile if public Plant() { this(“fern”); } is added t 
    the Plant class. 
    // 正确。this表示当前对象this("fern")就是调用当前的有参构造。E. 错误。语法有问题。
      

  5.   

    不好意思!C答案我看错了。Tree()语法错误。
      

  6.   

    父类中 Plant 没有定义无参的构造函数,只有一个有参的构造函数, 
    子类 Tree继承Plant 必须也得有个有参的构造函数,而且类型 参数必须和Plant中的构造函数相同 
    如果 Plant 中,没有定义构造函数,会默认调用无参的构造函数。