I am working on the Self
test in Chapter 2 of K & B book.
13. 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. } }
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.
14. 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. } }
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.
I have read the reference casting section of the chapter 2 and understood the same but still can't crack the above questions.
Please help me with explanations.
Thanks,
Jerry Ragland.