constructor already present. (Objective 5.4)
8. Given:
1. class Plant {
2. String getName() { return \3. Plant getType() { return this; } 4. }
5. class Flower extends Plant { 6. // insert code here 7. }
8. class Tulip extends Flower { } Which statement(s), inserted at line 6, will compile? (Choose all that apply.) A. Flower getType() { return this; } B. String getType() { return \C. Plant getType() { return this; }
D. Tulip getType() { return new Tulip(); } Answer:
正确: A, C, and D are correct. A and D are examples of co-variant returns, i.e., Flower and
Tulip are both subtypes of Plant.
错误:B is incorrect, String is not a subtype of Plant. (Objective 1.5)
9. 已知:
1. class Zing {
2. protected Hmpf h; 3. }
4. class Woop extends Zing { } 5. class Hmpf { } 哪个正确?可以多选
A. Woop is-a Hmpf and has-a Zing. B. Zing is-a Woop and has-a Hmpf.
C. Hmpf has-a Woop and Woop is-a Zing. D. Woop has-a Hmpf and Woop is-a Zing. E. Zing has-a Hmpf and Zing is-a Woop. 正确: D
10. 给定:
1. class Programmer {
2. Programmer debug() { return this; } 3. }
4. class SCJP extends Programmer { 5. // insert code here 6. }
哪个代码放到第5行,能够编译,可以多选 A. Programmer debug() { return this; } B. SCJP debug() { return this; } C. Object debug() { return this; } D. int debug() { return 1; }
E. int debug(int x) { return 1; }
F. Object debug(int x) { return this; } 正确: A, B, E, 和 F
11. 已知: class Uber {
static int y = 2;
Uber(int x) { this(); y = y * 2; } Uber() { y++; } }
class Minor extends Uber {
Minor() { super(y); y = y + 3; }
public static void main(String [] args) { new Minor();
System.out.println(y); } }
结果是? A. 6 B. 7 C. 8 D. 9
E. 编译失败 F. 抛出异常 答案: D
12. 哪些语句正确,可以多选
A. 内聚是OO的基本原则,主要与隐藏实现细节有关。
B. 内聚是OO的基本原则,确保一个类只能通过其他类的API访问其他类 C. 内聚是OO的基本原则,要确保类的功能比较单一、专注。 D. 内聚是OO的基本原则,单个对象可以被看成多种类型。
答案:C
13. 已知:
1. class Dog { }
2. class Beagle extends Dog { } 3.
4. class Kennel {
5. public static void main(String [] arfs) { 6. Beagle b1 = new Beagle(); 7. Dog dog1 = new Dog(); 8. Dog dog2 = b1;
9. // insert code here<父类类型变量赋值为子类时需要强制类型转换> 10. } 11. }
下面的哪个代码放在第9行,能够编译,可以多选 A. Beagle b2 = (Beagle) dog1; B. Beagle b3 = (Beagle) dog2; C. Beagle b4 = dog2; D. 以上代码都能够编译 正确: A 和 B
14. 给定下面的代码
1. class X { void do1() { } }
2. class Y extends X { void do2() { } } 3.
4. class Chrome {
5. public static void main(String [] args) { 6. X x1 = new X(); 7. X x2 = new Y(); 8. Y y1 = new Y(); 9. // insert code here 10. } 11. }
哪个代码放到第9行,能够编译,可以多选 A. x2.do2(); B. (Y)x2.do2(); C. ((Y)x2).do2(); D. 以上语句都不能编译 正确: C