Saturday, August 21, 2010

Polymorphism: GreekTest.java

Courtesy of Sun Web Learning Center

1. class Alpha { void m1() {} }
2. class Beta extends Alpha { void m2() { } }
3. class Gamma extends Beta { }
4.
5. class GreekTest {
6.   public static void main(String [] args) {
7.     Alpha [] a = {new Alpha(), new Beta(), new Gamma() };
8.     for(Alpha a2 : a) {
9.       a2.m1();
10.       if (a2 instanceof Beta || a2 instanceof Gamma)
11.         // insert code here
12.     }
13.   }
14. }

Which code, inserted at line 11, will compile, but cause an exception to be thrown at runtime?


A     a2.m2();
B     ((Beta)a2).m2();
C     ((Alpha)a2).m2();
D     ((Gamma)a2).m2();

D is correct.

a2.m2(); : Reference variable is of type Alpha, so the compiler sees that Alpha doesn't have m2 method
((Beta)a2).m2(); : Will run and compile because you are casting an Alpha reference variable as Beta. It is as if the reference variable is Beta, which has method m2()
((Alpha)a2).m2(); : You are casting reference variable Alpha as Alpha so it's just as if you would have written a2.m2();
((Gamma)a2).m2(); : Beta cannot be cast to Gamma. This is a downward cast and there is no guarentee that whatever Gamma can do, Beta can do

No comments:

Post a Comment