What happens in terms of memory when we convert sub class object to super class object.?
One o = new Two();
What happens is that a Two
instance is created, and the reference is assigned to o
.
This doesn't change the Two
instance in any way. It is not "converted". It remains a Two
.
What happens in terms of memory when we convert super class object to sub class object.?
Two t = (Two) new One();
What happens is that a One
instance is created, and its type is tested to see if the One
is a Two
. Since it isn't ... a ClassCastException
is thrown immediately.
(Following that, the One
instance that was just allocated will be unreachable and a candidate for garbage collection ... the next time that the GC runs.)
In fact, you probably meant this:
One o = new Two();
Two t = (Two) o;
What happens in this case is that the first statement creates a Two
instance and assigns its reference to o
. Then in the second statement, the type of the object refered to by o
is tested to see if it "is-a" Two
. Since it is ... the reference is then assigned to t
.
Once again, this doesn't change the Two
instance in any way. It is not "converted". It remains a Two
.
Can you give some detail about how the memory will be allocated.? I mean "when Two class object is created, memory will be allocated for Two's members and One's members as well (reason being One is super class for Two)" and will be referred by 't'.
That is correct
When we do "One o = new Two()", we will be able to access only One class members.
That is correct.
When we are converting like this (sub class object pointed by super class reference), what exactly happens internally..?
All that happens is that the compiler & runtime "forget" that o
actually refers to a Two
, and only permits you to use the reference to access the fields / methods defined by the One
class.