Google+

Like Us On Facebook


Total Pageviews

104. Using 'super' keyword to access the methods of 'superclass'






If the 'subclass' has declared the same method that is already available in 'superclass' then the subclass uses 'super' keyword to access the method declared in the 'superclass'.

Example - super.methodname( );

Lets implement this on Eclipse IDE:

1. Create 'Superclass' superclass as shown below:



2. Create 'Subclass' subclass as shown below:



3. Create 'SuperMethodDemo' class to call the methods available and methods inherited by the 'Subclass' as shown  below:



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



Download this project:

Click here to download this project containing 'Superclass', 'Subclass' and 'SuperMethodDemo' class files used in this post (You can download this project and import into Eclipse IDE on your machine)

So now we have come to know that 'super' keyword can be used to access the instance variables and methods of the 'superclass' that have hidden by the instance variables and methods of the 'subclass'. We can also use 'super' keyword to call the Superclass constructors.




Please comment below to feedback or ask questions.

How to call the 'Superclass' constructors using the 'super' keyword will be explained in the next post.




3 comments:

bellam said...

void printText() in subclass is not working. We have to define as Public. Can you please check once please.

Arun Motoori said...

@bellam - Its working for me. Please double check.

Use the below code to create different Classes and double check at your end.

........................................

package packageThree;

public class SuperClass {

void printText(){

System.out.println("printing text from SuperClass");

}

}

................................

package packageThree;

public class SubClass extends SuperClass {

void printText(){

System.out.println("printing text from SubClass");

}

void calledMethod(){

printText();

super.printText();

}

}

...........................

package packageThree;

public class CallingClass {

public static void main(String[] args) {

SubClass sc = new SubClass();

sc.calledMethod();

}

}

......................................

bellam said...

i declared public in super class()
package babu15;

public class superclass {

int a=5;
public void printvar1()
{
System.out.println("sample1 print in superclass");
}
}


changing the same in subclass worked,else it didn't worked.Thanks Aroon.

Blog Index