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:
5. Observe that the output is displayed in the console as shown below:
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:
void printText() in subclass is not working. We have to define as Public. Can you please check once please.
@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();
}
}
......................................
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.
Post a Comment