super
keywordThe super
keyword in Java is used in classes where inheritance is involved. Inside a child class that inherits from the parent class, the super
keyword allows us to refer to members (variables and functions/methods) of the parent class (also known as the superclass).
The super
keyword is particularly useful when an
Note:
When a function has been overridden, calling it from within the child class doesn't allow the method of the parent class to be called (because it has been overridden in the child class). This is illustrated below:
class Parent{// overridden methodpublic void exampleFunction(){System.out.println("exampleFunction() of Parent called!");}}class Child extends Parent{// overriding the exampleFunction method of the parent/super class@Overridepublic void exampleFunction(){System.out.println("exampleFunction() of Child called!");}public void callExampleFunction(){exampleFunction(); // calling the overridden function from within the child class}}class Main{public static void main(String[] args){Child Child1 = new Child();Child1.callExampleFunction();}}
To access an overridden method of a parent class from within a child class, we can use the super
keyword. This is demonstrated below:
class Parent{// overridden methodpublic void exampleFunction(){System.out.println("exampleFunction() of Parent called!");}}class Child extends Parent{// overriding the exampleFunction method of the parent/super class@Overridepublic void exampleFunction(){System.out.println("exampleFunction() of Child called!");}public void callExampleFunction() // this method in the child class// has the same name and the same number of parameters as the method// in the parent class, and hence, the parent class's method gets overridden{exampleFunction(); // calling the overridden function from within the child classsuper.exampleFunction(); // using the super keyword to access the parent's version of this function, which was overridden}}class Main{public static void main(String[] args){Child Child1 = new Child();Child1.callExampleFunction();}}
In conclusion, the super
keyword allows both versions of the method to be called. Here, super.methodName()
is used to access the parent class's method (which has been overridden) and methodName()
is used to access the child class's method.
Free Resources