124. Accessing the overiding method of sub-class using superclass object

If you have the same method of same type in Superclass and Subclass, then it means that the method in subclass overrides the method in superclass. In order to access the method in superclass, we can directly create an object to superclass and call it. But if we have to use the superclass object to call the overridden method in subclass we have to assign the reference of subclass to the superclass object as shown below:

Example: (Suppose we have sampleMethod( ) created in both superclass and subclass)

Superclass object1 = new Superclass( );   //Creating object for Superclass
object1.sampleMethod( );   //This will call the method in superclass 
object1 = new Subclass( );   // Assigning the reference of subclass to superclass object 'object1'
object1.sampleMethod( );  //This will call the overridden method in subclass instead of the same method in superclass

Lets implement this on Eclipse IDE:  (Access the members of sub-classes using the object created for superclass)

1. Create superclass 'Superclass' containing a method 'sample( )' as shown below:

2. Create subclass 'Subclass' which inherits 'Superclass' and also overrides the same  method 'sample( )' as shown below:

3. Create class 'SuperclassObjectDemo' to create an object for superclass and access the overridden method of sub-class using the  object created for 'superclass' as shown below:

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

Download this project 

Click here to download the project containing the 'Superclass', 'Subclass' and 'SuperclassObjectDemo' 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.

'Interface References' will be explained in the next post.

1 comment:

nvn-naveen said...

Hi Arun,
After providing the reference of SubClass to an Object, what if we want to call the Method of SuperClass?
Do we need to provide the reference of the SuperClass and call the method?