Originally posted by Subhabrata Sen:
Consider the following piece of code:
class Base
{
public void show(){
System.out.println("BASE");
}
}
class Derived extends Base
{
public void show(){
System.out.println("DERIVED");
}
}
public class BaseDerived
{
static public void main(String[] args)
{
Base base = new Base();
Derived derive = new Derived();
base = derive; // 1
base.show(); // 2
derive = (Derived)base; // 3
derive.show(); // 4
}
}
Could anyone answer the followind questions:
Q.1.: If I delete line 1 and run the program the output is:
BASE
java.lang.ClassCastException at BaseDerived.main(BaseDerived.java:26)
Exception in thread "main"
Q.2: If I run the above code as such, with out deleting any lines the output
is:
DERIVED
DERIVED
In the first line of the main method, base is a reference to a Base object.
In the second line of the main method, derive is a reference to a Derived object.
Since Derived is a subclass of Base, it is legitimate to have base become an alias of derive which is what happens in line 1.
Then you can call the show method on base and it will call the method which was overridden. The runtime type of the object is still Derived.
You can also then legitimately cast the type of the reference of base to a Derived reference because base is already a reference to a Derived object.
If you do not have line 1, you will get a compile-time error because you cannot cast base, which is a reference to the Base object, to be a reference to a Derived object.
A Base object is not a Derived object, however a Derived object is a Base object.
[ June 15, 2006: Message edited by: Keith Lynn ]