How to override a method using the super keyword

The super keyword

The 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 overridden methodAn overridden function is one which has the same name and number of parameters in both the parent and the child class. needs to be called. In this Answer, we'll explore how this keyword can be used for this purpose.

Note:

  • To learn more about the super keyword, refer to this link.

  • To learn more about method overriding in Java, refer to this link.

Overriding

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 method
public void exampleFunction()
{
System.out.println("exampleFunction() of Parent called!");
}
}
class Child extends Parent
{
// overriding the exampleFunction method of the parent/super class
@Override
public 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 method
public void exampleFunction()
{
System.out.println("exampleFunction() of Parent called!");
}
}
class Child extends Parent
{
// overriding the exampleFunction method of the parent/super class
@Override
public 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 class
super.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

Copyright ©2025 Educative, Inc. All rights reserved