by Dinesh Thakur

A subclass inherits methods from a superclass. However in certain situations, the subclass need to modify the implementation (code) of a method defined in the superclass without changing the parameter list. This is achieved by overriding or redefining the method in the subclass.

To override a subclass's method, we simply redefine the method in the subclass with the same name, same return type and same parameter list as its superclass counterpart. When the method with the same name exists in both the superclass as well as in the subclass, the object of the subclass will invoke the method of the subclass, not the method inherited from the base class.

Now the question arises that can we invoke the overridden method of the superclass from the-subclass. The answer is yes and it is possible in Java using the super keyword followed by a dot operator and the overridden method along with the list of arguments enclosed in parentheses. Its syntax is

super.overriddenMethod(arguments) ;

The following program illustrates the concept of method overriding.

class Person

{
     private String name;
     private int age ;
     Person(String n,int pAge)
     {
       name = n;
       age=pAge;
     }
     public String toString()
     {
        return("Name : "+ name+"\n"+  "Age  : "+age+"\n");
     }
}
  class Student extends Person
{
     private int rollno;
     private String stuClass ;
     private double percentage;
     Student(int rno,String n,int page,String c,double p)
     {
       super(n,page); //call superclass constructor
       rollno = rno;
       stuClass=c;
       percentage = p;
     }
     //override toString()method
     public String toString()
    {
        return("Rollno : "+ rollno +"\n"+ super.toString() +"Class : "+stuClass +"\n"+"Percentage : "+percentage);
    }
}
class OverridingMethods
{
    public static void main(String[] args)
   {
       Student s=new Student(1,"Dinesh Thakur",35,"MCA",90.5);
       System.out.println(s.toString());
   }
}

Overriding Methods in Java