I have developed this basic doubt and need some light over it...
The output i see is: Hello from Class B Hello from Class A Class B Class B < ------ have the doubt here
My doubt is, when we can access the original value for dummyStr [i.e the value assigned in the super class] by typecasting the ClassB instance to ClassA, why can't we access the implementation for the method in ClassA via typecast?
I understand i can get hold of the super class implementation for the method via the super keyword, but want to understand, why is the reference to ClassA obtained by typecasting, not executing the impl in ClassA. [ June 24, 2008: Message edited by: Anupam Bhatt ]
Instance variables are not polymorphic. You can't "override" a variable in a superclass, you can only hide it. By casting to the parent type, you can effectively "move the subclass variable out of the way," so you can see the hidden copy in the parent. Which variable you get depends on the type of the reference to the object, and it's chosen at the time the program is compiled.
Methods are polymorphic. That means that the JVM decides which method to call while the program is running. The choice is made based on the actual class of the object you call the method on. There's no way to "move the subclass method out of the way" -- it just doesn't work like that. There's no way for an outside class to call the parent version of the method.
Check out this story to understand more -- I guarantee it will help.
Assuming the following is coded in the ClassB class.
ClassB is a subtype of ClassA. Even though the instance of ClassB can be referenced as a ClassA, the this operator points to the actual concrete class not the reference type. So, in your example, since you are calling this.returnString(), you are calling the implementation coded in ClassB.
The fact that you are storing a reference to an instance of ClassB as a ClassA does not change the semantics of the this operator.
Creating a ClassA reference variable to an instance of ClassB and casting the ClassB object to populate the reference does not change the object. A ClassB object will always be a ClassB object...forever. Casting it, storing a reference variable to it with a different permissible type does not change this. Never.
P.S. This is a awkward way to code anyway. Much better to program with composition and interfaces. [ June 24, 2008: Message edited by: James Clark ]