How to call Base class’s overridden method from Derived class in java

In this article we will discuss how to call parent class’s overridden method from a derived class method in Java.

Suppose we have a Base class which has a function display() i.e.

class Base
{
	public void display()
	{
		System.out.println("Base :: display");
	}
}

Now we will create a Derived class that will extend this Base class i.e.

class derived extends Base

In this class we will override the display() function i.e.

class derived extends Base
{
	public void display()
	{
		//.......
	}
}

Now if we create a Derived class object and call this overridden display() function from it , then due to dynamic binding in Java, always derived class display() method will be called i.e.

Base baseRef = new derived();
		
// Due to dynamic binding, will call the derived class
// display() function
baseRef.display();

Now, if we want to call Base class’s display() function from the Derived class’s display() function, then how to do that ? Answer is using super keyword.

Calling Parent class’s overridden method from Child class’s method using super keyword

Calling,

super.display()

from Derived class function will call base class version of display() function i.e.

class derived extends Base
{
	public void display()
	{
		System.out.println("Derived :: display Start");
		
               // Call the Base class function display()
		super.display();
		
		System.out.println("Derived :: display End");
	}
}

Complete code is as follows,

package com.thispointer.inheritance.example1;

class Base
{
	public void display()
	{
		System.out.println("Base :: display");
	}
}

class derived extends Base
{
	public void display()
	{
		System.out.println("Derived :: display Start");
		// Lets call the base class function display()
		super.display();
		
		System.out.println("Derived :: display End");
	}
}


public class Example {
	public static void main(String[] args) {
		
		Base baseRef = new derived();
		
		// Due to dynamic binding, will call the derived class
		// display() function
		baseRef.display();

	}

}

Output:

Derived :: display Start
Base :: display
Derived :: display End

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top