Google+

102. Assigning subclass reference to superclass reference







Here reference means object.

We can assign an object of subclass to object of superclass from which the subclass is derived.

Example: 

Box plainobject = new Box( );
BoxWeight weightobject = new BoxWeight( );

plainobject = weightobject;   //Assigning an object of subclass to object of its superclass

Lets implement this on Eclipse IDE:

1. Create 'Box' class as shown below and save:



2. Create 'BoxWeight' as subclass for 'Box' superclass as shown below and save:



3. Create 'ReferenceDemo' class to demo what happens before and after assigning the subclass object to superclass object as shown below:


4. Save and Run the 'ReferenceDemo' class
5.Observe that the output is displayed in console as shown below:



Understanding the output:

Overall, the output has printed three lines. All the lines are printing the volume of the boxes.

After viewing the first line, its very clear that the volume of weightbox is printed (i.e. we have passed 10, 10, 10, 55 values to the volume( ) method in BoxWeight class and it resulted 10*10*10 as result and hence it printed 1000 as weightbox volume.

After  viewing the second line in the output, its very clear that the volume of plainbox is printed (i.e. we have passed 1,1,1 values to the volume( ) method in Box class and it resulted 1*1*1 as result and hence it printed 1 as plainbox volume.

So now we know that volume of weightbox is 1000 and volume of plainbox is 1.

But here is the twist, after assigning the weightbox object to plainbox object, the arguments of the plainbox object got replaced with the arguments of the weightbox object. i.e. 1,1,1 are replaced with 10,10,10.

But, weightbox object has four arguments i.e. 10,10,10,55. Since the plainbox object has only three arguments its takes only 10,10,10 and ignores 55.

So, after viewing the third line in the output, now its very clear that the volume of plainbox is printed (i.e. 10,10,10 arguments are passed instead of 1,1,1 and hence 10*10*10 i.e. 1000 is printed instead of 1 ).

Download this project:

Click here to download the project containing 'Box', 'BoxWeight' and 'ReferenceDemo' class files used in this post (You can download this project and import into Eclipse IDE on your machine)




Please comment below to feedback or ask questions.

'super' keyword will be explained in the next post.



No comments: