Google+

191. Assigning SubClass reference to SuperClass object and accessing members







Pre-requisite -

On assigning the object of SubClass to its SuperClass object, the SuperClass object can only access the members of the SuperClass. Though we have assigned the object of SubClass to SuperClass, the SuperClass object cant access the members of the SubClass.

Example -

SubClass subobject = new SubClass( );

SuperClass superobject = subobject;


After assigning the SubClass object to the SuperClass object, using SuperClass object 'superobject' -

  • We can access the members of the SuperClass
  • We can access the members inherited by the SubClass from the SuperClass
  • We cannot access the members of the SubClass
Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a new Java Project 'Project 24' as shown below -



2. Create a .java Class 'SuperClass' , define an instance variable 'a' and assign a value to it as shown below -


3. Create a .java Class 'SubClass', define an instance variable 'b' and assign a value to it as shown below -


4. Let the 'SubClass' inherit the 'SuperClass' by writing the following statement -


5. Create another .java Class 'ClassOne' with main( ) method as shown below  to create objects and access the members of SuperClass and SubClass Classes -


6. Create an object for the SubClass as shown below -


7. Define an object for the SuperClass (Just define don't create) as shown below -


8. Now assign the subclass object to the SuperClass object as shown below -


Now SuperClass object 'supobject' has the reference of the SubClass object 'subobject'. Now lets see what we can access using the SuperClass object 'supobject' by following the below steps.

9. Access the instance variable 'a' of the SuperClass using the SuperClass object 'supobject' as shown below and print the value -


10. You may think that, on assigning the subclass object to the superclass object, we can access the members of the subclass also using the superclass object. But it is not possible to access the members of the subclass using the superclass object even though the object of subclass is assigned to the superclass object. Now lets try to access the members of the subclass using the superclass object 'supobject' as shown below -


11. Comment the above statement as shown below -


12. Run the 'ClassOne' Class as it is containing the main( ) methods and the objects to access the members of the other Class.

13. Observe that the output is displayed in the console as shown below -



When you assign a subclass object reference to superclass object reference, using superclass object -

  1. You can access the members of the SuperClass
  2. You cannot access the member of the SubClass
  3. You can access the members inherited by the SubClass from the SuperClass.




Please comment below to feedback or ask questions.

Defining objects for abstract classes will be explained in the next post.






No comments: