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. 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是一个方法也不是一个构造函数。
我这样理解对吗?不对的话,哪儿错了???谢谢。。
解决方案 »
- servlet 关于得到的request信息是乱码
- 一个Java类被虚拟机加载时 静态变量被静态方法初始化赋值 以后调用时用哪个?
- jeditorPane编辑的问题
- if (request.getParameter("act").equalsIgnoreCase("save"))这条语句为什么会抛出异常
- 请教各位达人!
- 怎样在API文档中查找一个函数的详细资料
- 驱动程序找不到Class.forName("oracle.jdbc.driver.OracleDriver");,在程序中还要设置什么?
- 急急急!!!我该怎样去面试?
- 讨论,如果微软封杀java,java还能活得下去吗?是不是我们又要改做C#?
- 大企业的算法面试题,等你来挑战。
- 求助,在线等答案
- 求html视屏教学
原因是Tree没有定义构造函数,那么默认是调用父类中无参构造函数进行初始化public Plant() { ... },但是在Plant中只定义了带参数的构造函数。或者还有一种方式就是去掉Plant中的构造函数,那么Plant默认就调用Object(){...}进行初始化,这样就不是出错了
子类 Tree继承Plant 必须也得有个有参的构造函数,而且类型 参数必须和Plant中的构造函数相同
如果 Plant 中,没有定义构造函数,会默认调用无参的构造函数。
正确答案: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. 错误。语法有问题。
子类 Tree继承Plant 必须也得有个有参的构造函数,而且类型 参数必须和Plant中的构造函数相同
如果 Plant 中,没有定义构造函数,会默认调用无参的构造函数。