Page: 17
8. OOPs
71. Given: 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. } Which, inserted at line 9, will compile? (Choose all that apply.) A. Beagle b2 = (Beagle) dog1; B. Beagle b3 = (Beagle) dog2; C. Beagle b4 = dog2; D. None of the above statements will compile Answer: -> A and B are correct. However, at runtime, A will throw a ClassCastException because dog1 refers to a Dog object, which can’t necessarily do Beagle stuff. -> C and D are incorrect based on the preceding. (Objective 5.2). 72. Given the following, 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. } Which, inserted at line 9, will compile? (Choose all that apply.) A. x2.do2(); B. (Y)x2.do2(); C. ((Y)x2).do2(); D. None of the above statements will compile. Answer: -> C is correct. Before you can invoke Y’s do2 method you have to cast x2 to be of type Y. Statement B looks like a proper cast but without the second set of parentheses, the compiler thinks it’s an incomplete statement. -> A, B and D are incorrect based on the preceding. 73. Given: class Bird { { System.out.print("b1 "); } public Bird() { System.out.print("b2 "); } } class Raptor extends Bird { static { System.out.print("r1 "); } public Raptor() { System.out.print("r2 "); } { System.out.print("r3 "); } static { System.out.print("r4 "); } } class Hawk extends Raptor { public static void main(String[] args) { System.out.print("pre "); new Hawk(); System.out.println("hawk "); } } What is the result? A. pre b1 b2 r3 r2 hawk B. pre b2 b1 r2 r3 hawk C. pre b2 b1 r2 r3 hawk r1 r4 D. r1 r4 pre b1 b2 r3 r2 hawk E. r1 r4 pre b2 b1 r2 r3 hawk F. pre r1 r4 b1 b2 r3 r2 hawk G. pre r1 r4 b2 b1 r2 r3 hawk H. The order of output cannot be predicted. I. Compilation fails. Answer: -> D is correct. Static init blocks are executed at class loading time, instance init blocks run right after the call to super() in a constructor. When multiple init blocks of a single type occur in a class, they run in order, from the top down. -> A, B, C, E, F, G, H, and I are incorrect based on the above.
Page: 17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|