Method Overriding in Java with Example

Method overriding is another important feature in java which is used quite often in java programming. It is also very often asked with java programmers specially with beginners in interviews. This tutorial covers different details about method overriding along with some questions which will clear your doubts about method overriding.

What is method overriding

In java a child class can define methods with same signature as in parent class, if we do so, we call this as method overriding. Method overriding is a technique in java which allows java programmers to write methods in child class with same signature as in parent class.

What is method signature ?

In a method declaration, the method name along with it's parameter types is known as method signature. For example in a method declaration public static int add(int a, int b){}, the signature will be add(int, int). Two methods will be of same signature if their signature exactly matches with each other.

The parent class method that get's overridden is known as overridden method while the child class method that overrides the parent class method is known as overriding method. Method overriding can exist only in parent-child relationship which is in case of inheritance only.

Below code shows an example of method overriding in java :

 class A {
    int add(int a, int b) {  }
    int subtract(int a, long b) {  }
 }
 
 class B extends A {
    int add(int c, int d) {  } // Overrides parent class method
    int subtract(long c, int d) {  } // Won't override parent class method
 }   

Here add method of child class B overrides the add method of parent class A, since both methods have same signature. Here subtract method is not overridden as the signature of both methods are different, instead it will be an overloaded method.

 subtract(int, long) // Signature of A's class method
 subtract(long, int) // Signature of B's class method  

What exactly does it mean when a child class method overrides the parent class method

It simply means the child class method will get preference over the parent class method when you will call that method using the child class object. Though the parent class method was inherited in child class but as it was overridden in child class, the JVM gives preference to child class method over the parent class method.

Method overriding rules in Java

  • There must be parent child relationship which means inheritance must be there.
  • The signature of parent and child class methods must be same.
  • If return type of parent class method is a primitive type, then child class method must also have the same return type. For example if return type of parent class method is int, then child class method's return type must also be int. Using any other return type would result in compilation error.
  • If return type of parent class method is a non primitive type then a covariant return type can also be used in child class method from java 5. Refer next tutorial to know about covariant return type.
  • The access modifier of child class method should not be more restrictive. It should be same or more accessible modifier. For example if parent class method has default modifier, then child class can have default, protected or public modifier. Using more restrictive modifier would result in compilation error.

Can we override every method of parent class ?

No, private, static and final methods of parent class can not be overridden in child class.

Real time example of method overriding in Java

We can take parent child relationship as an example of inheritance. Many of the real world habits of a parent child can be overridden in nature. For example, a parent child can have a common behavior singing, where in the singing behavior of a child may be different than his parent. One may be classical singer while other is a rock singer.

Similarly there can be other behaviors as well like dance, speak, teach etc where parent and child can have different approach of doing the same behavior. The same can be applicable for other type of species or things as well.

Method overriding program in Java

 class Person {
    void teach() {    
      System.out.println("I can teach");
    } 
 }
 
 class Teacher extends Person {   
    void teach() {
      System.out.println("I teaches English");
    }    
    public static void main(String [] args) {
      Teacher teacher = new Teacher();  
      teacher.teach();
      Person person = new Teacher();  
      person.teach();
      Person person2 = new Person();  
      person2.teach();     
    }
 }

Output:

I teaches English
I teaches English
I can teach

Here the teach method is in both the classes, Person and Teacher. The teach method of person class is overridden in Teacher class. Let's see the sample code below to make it more clear :

 class A {
   int add(int a, int b) {  }
   int add2(int a, int b) {  }
   int add3(int a, int b) {  }
   int add4(int a, int b) {  }
   int add5(int a, int b) {  }
 }
 
 class B extends A {
   int add(int c, int d) {  }  // It will override parent class method.
   long add2(int c, int d) {  } // It won't compile, return type must be same.
   private int add3(int c, int d) {  } // won't compile, can not reduce access modifier
   int add4(int c, int d, int e) {  }  // won't override, will act as an overloaded method
   int add5(int c, float d) {  } // won't override, will act as an overloaded method
 }   

How does JVM decides which method to call at run time

The JVM checks the actual type of the object which is calling the method, then on that actual type it calls the corresponding method. The actual type of an object is the type which is used with new keyword. For example when you create the object as new Teacher(), it's actual type will be of Teacher type, so it will call the Teacher class method, no matter whether this object was assigned into Teacher class type or Person class type.

 Teacher teacher = new Teacher();  // Actual type is Teacher
 Person person = new Teacher();  // Actual type is Teacher
 Person person2 = new Person();  // Actual type is Person    

Use of method overriding in Java

  • The main reason to use method overriding is to change/modify the behavior of parent class method as per the requirement in child class. Now you may think that why not to change the parent class method itself ?, the reason is, that parent class may have been inherited by many other classes as well. If you modify the method of parent class, that will be reflected in all the subclasses whether they need that change or not, which may affect the functionality of your project, so it's not a good practice at all.
  • Method overriding is used to achieve run time polymorphism in java which is an essential concept of object oriented programming.

When we should use method overriding

When you find that the parent class method is not full-filling the child class requirement, in other words when you have a need to change/modify the behavior of an existing method of parent class inside child class, you should use method overriding. Many times in real world projects when we create a more specific class from a generic class, we need to use method overriding to change the behavior of generic class method.

For example let's suppose you have an Animal class having a method as sound, now if you create classes like Dog and Cat from Animal class, you would be needed to change/override the behavior of sound method in Dog and Cat classes since a dog barks whereas a cat meows.

Example of method overriding in pre-defined java classes

There are many java classes where method overriding is used, some of the frequently used classes like StringBuffer, StringBuilder, ArrayList, HashMap etc has many overridden methods. The StringBuilder class has override many methods of AbstractStringBuilder class like append(String str), substring(int start), indexOf(String str) etc.

Advantages of method overriding in Java

  • The main advantages of using method overriding is that it gives child class the ability to change the behavior of parent class method as per the requirement. Child classes can re-define the method which is suitable or specific to them.
  • Another advantage of overriding is that it provides multiple implementation of same method, one can call parent or child class method as per the need.
  • It gives you ability to achieve run time polymorphism which is an essential concept of OOPS.
★★★
  • Method overriding is an example of run time polymorphism in java.
  • Call to overridden method is resolved at run time not at compile time.
  • Only the instance methods can be overridden in Java.
  • Instance variables can not be overridden in child class.
  • We can not override main method as it is a static method.
  • Overriding method cannot throw any checked exception if parent class doesn't throws any exception.