Search code examples
javaoopinheritancepolymorphism

What happens when a subclass object is assigned as a superclass object


So I have a question about a superclass A and subclass B, where A has 2 public variables and B has 1 more.

I saw this snippet of code:

A a = new A();
B b = new B();
a = b; 

What does that last line do? I don't really understand what actually happens when you use "=" between 2 classes in an inheritance relationship.


Solution

  • It's simple assignment. = is an assignment operator.

    Lets be clear of below points.

    1. In Java when an Object is created and it is accessible via. reference. A reference refer to an Object.
    2. At a time one reference can refer to only one object
    3. A reference of type X can refer to an object of type X or any sub types (extending in case X is a class or implementing if X is an interface).

    Now Suppose there are two classes Super and Sub such that Sub extends Super.

     SuperClass reference = new SubClass();  
    

    This is allowed as SubClass inherits from SuperClass. Above we have an object of type SubClass created in the heap and it is accessible via. reference named reference

    Note that a reference of type SubClass can not refer to object of SuperClass. Lets see in brief why so ?. If the reference of type SubClass was allowed to refer an Object of type SuperClass then it would have been allowed to invoke additional methods (functions) defined by SubClass (SubClass would have inherited all methods of SuperClass and would also have defined few additional methods). Now this would have made the application to crash as the Object of SuperClass only has methods defined in SuperClass but does not have any additional methods defined by SubClass. Hence compiler prevents it during compile time. Its a compile time error to have a reference of type SubClass referring to an object of type SuperClass

    Now lets look at the code as mentioned in the question

     SuperClass a = new SuperClass();
     SubClass b = new SubClass();
     a = b; 
    

    Line 1 : We have an object of SuperClass being referred by a variable of type SuperClass named a

    Line 2 : We have an object of SubClass being referred by a variable of type SubClass named b

    Line 3 : We have an assignment where a is assigned to refer the same object as referred by b. So now we have both references referring to the object of type SubClass created at line 2. Object of typer SuperClass created at line 1 (with the current available code mentioned in the question) is not having any references so it is eligible for garbage collection.