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:
5. Observe that the output is displayed in the console as shown below:
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.
1 comment:
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?
Post a Comment