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这个题是要在Plant类里面添加无参构造器吧,我想问一下this(”fern”)这样写是什么意思?
    谢谢。。

解决方案 »

  1.   

    this("fern")就是说显式地调用该类的Plant(String)构造函数。
    你的代码里定义的Plant本身没有默认构造函数,如果你就加上了D选项所说的代码,就是定义了默认构造函数,让默认构造函数去调用String版本的构造函数,这样其派生类在实例化对象的时候就能正常按顺序从基类到派生类实例化对象了。
      

  2.   

    记住如果要在Plant类中调用构造函数,必须写成this("fern");而不能写成Plant("fern");否则会出现编译错误,这是JVM规定的,记下来就可以了。