Here is a code snippet:
Consider the following classes:
class A implements Runnable{ ...}
class B extends A implements Observer { ...}
and the declarations :
A a = new A() ;
B b = new B();
Which of the following
Java code fragments will compile and execute without throwing exceptions?
(a)Object o=a; Runnable r = o;
(b)Object o=a; Runnable r = (Runnable)o;
(c)Object o=a; Observer ob = (Observer)o;
(d)Object o=b; Observer o2 = o;
(e)Object o=b; Runnable r = (Runnable)b;
The correct answer is b and e. I understand the concept of using object reference to its sub-class object (e.g. Object o=a). One of the JavaRanch CampFire stories explain it really well. But I am not quite sure about this:
"If the reference type is an INTERFACE, the object it refers to MUST be an object from a class which implements the interface (either directly or through inheritance)." -- Quote from How my Dog learned
Polymorphism, JavaRanch
Can anybody illustrate the above concept using the code snippet above? Thanks