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

Calling base class’s overridden method from derived class in java.

In this article we will discuss about calling base class/parent class’s overridden method from derived class/sub class.

As we know,

  • Super class : A class which is inherited is called super class or parent class or base class. (Means this class’s properties are inherited by another class)
  • Sub class : A class which inherits is called sub class or child class. (Means this class inherits the properties of another class)

Suppose we have a parent class Main having show() function

class Main
{
 public static void main(Strings args[])
 {
   System.out.println("This is base class show function")
 }
}

And a derived class Mainsub extends the parent class Main

class Mainsub extends Main
{
 public void show()
 {
    //.......
 }
}

And now if we will create a derived class object and will call the show() method from it, then show() method of derived class will be called due to the concept of dynamic binding in Java. Means we are here assigning sub class object to super class reference variable.

Main baseRef = new Mainsub();
// Due to dynamic binding, will call the derived class
// show() function
baseRef.show();

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

In java, there is a super key word which can be used to call  super class methods from a subclass.

Syntax- super.superclass_methodname()
Without Super() :
class Main 
{
        public void show()
        {
        System.out.println("This is base class show function") ;
        }
}
class Mainsub extends Main
{
 public void show()
 {
   System.out.println("This is derived class show function") ;
 }
}

class Test
{
        public static void main(String args[]) 
        {
             // Derived class method will be called
             Main p=new Mainsub();
             p.show();    
        }
}
Output :
This is derived class show function
With Super() :
class Main
{
        public void show()
        {
        System.out.println("This is base class show function") ;
        }
}
class Mainsub extends Main
{
 public void show()
 { 
   System.out.println("This is derived class show function") ;
   // base class show() method called
   super.show();
 }
}

class Test
{
        public static void main(String args[]) 
        {
             Main p=new Mainsub();
             p.show();    
        }
}
Output :
This is derived class show function
This is base class show function