Java Method Overriding – Learn its Importance and Rules with Coding Examples

In the last tutorial, we have learned the concept of Polymorphism in Java. We covered the two kinds of polymorphism in Java and the process of implementing them in Java. We know that static polymorphism can be achieved at compile time with the help of Method Overloading, while dynamic polymorphism can be achieved at run/execution time with the help of Method Overriding. In this article, we will study in detail about Method Overriding in Java with its rules and examples.

What is Java Method Overriding?

Method Overriding is a feature that allows us to redefine the method in the subclass or derived class which is already defined in its parent class or superclass. In any object-oriented programming language, we can implement Method Overriding only when two classes have ‘Is-a’ relationship of inheritance between them.

Using Method Overriding, a derived class or child class can provide a specific implementation of a function or method that is already defined in one of its parent classes. When a method of a derived or sub-class has the same name, same return type or signature and with the same arguments as a method in its parent class, then we say that the method in the superclass is being overridden by the method in the subclass. This concept when a method of a subclass overrides the same method in its superclass, but with a different implementation, is called Method Overriding.

Importance of Java Method Overriding

Now you must be thinking about what is the need for using Method Overriding. So let’s discuss the uses and importance of Method Overriding in Java.

  • One of the benefits of Method Overriding is the ability to provide a specific implementation or definition of a method in a subclass, which already exists in its superclass. This method can be overridden in the subclass according to the requirement.
  • It is also useful in the implementation of Runtime or Dynamic Polymorphism in which the method is invoked during the execution of the program. Basically, the type of object and not the type of reference variable decides which method is going to be executed at the runtime.

The following figure illustrates the Method Overriding in Java where the method draw() is being overridden in the three subclasses (Square, Circle, and Hexagon) of their base class or superclass Shape.

Java Method Overriding

Example and Code to Understand Method Overriding in Java

Let’s take a simple example to understand the concept of Method Overriding. We have two classes: A parent class Shape and a child class Circle. The Circle class inherits the Shape class. Both the classes have a common method void draw(). The child class is giving its own implementation to the draw() method. In other words, it is overriding the draw() method of the parent class.

The purpose of Method Overriding is that if the derived class wants to give its own implementation it can give by overriding the method of the parent class. When we call this overridden method, it will execute the method of the child class, not the parent class. This example is illustrated below with the help of code.

Code to understand the concept of Method Overriding:

package com.techvidvan.methodoverriding;
//Base class
class Shape
{
  void draw()
  {
    System.out.println("Inside the method of Parent class ");
    System.out.println("Drawing Shapes");
  }
}

//Derived class
class Circle extends Shape
{
  //Overriding method of base class with different implementation
  @Override
  void draw()
  {
    System.out.println("Inside the overridden method of the child class ");
    System.out.println("Drawing Circle");
  }
}

//Driver class
public class MethodOverridingDemo
{
  public static void main(String args[])
  {
    //creating object of Base class Shape
    // If a Parent type reference refers
    // to a Parent object, then Parent's draw() method is called

    Shape obj = new Shape();
    obj.draw();

    // If a Parent type reference refers to a Child object Child's draw() method is called.
    //This is called RUN TIME POLYMORPHISM.

    Shape obj1=new Circle();
    obj1.draw();
  }
}

Output:

Inside the method of Parent class
Drawing Shapes
Inside the overridden method of the child class
Drawing Circle

Rules for Method Overriding in Java

Java Method Overriding Rules

1. Overriding Access-Modifiers

We can change the access modifier for an overriding method. In the derived class, while overriding a method, we can provide less restriction, but not more, restrictive access than the access of the overridden method of the superclass.

For example, the method declared as public in the super-class cannot be made private or protected while overriding it in the subclass. Similarly, the protected method can be made public but not private in the subclass. If we provide lesser access in the subclass than that in the superclass, then we will get a compile-time error.

Dive a little deep into the concept of Access Modifier in Java with Techvidvan.

Note: We cannot override private methods !!

Code to illustrate Method Overriding and Access Modifiers:

package com.techvidvan.methodoverriding;
//Parent Class
class ParentClass
{
  // private methods are not overridden
  private void parentMethod1()
  {
    System.out.println("Inside the parentMethod1() of ParentClass");
  }

  protected void parentMethod2()
  {
    System.out.println("Inside the parentMethod2() of ParentClass");
  }
}

class ChildClass extends ParentClass
{

  private void parentMethod1()
  {
    System.out.println("Inside the parentMethod1() of ChildClass");
  }

  // overriding method with more accessibility
  @Override
  public void parentMethod2()
  {
    System.out.println("Inside the parentMethod1() of ChildClass");
  }
}
//Driver class
public class MethodOverridingDemo
{
  public static void main(String args[])
  {

    ParentClass obj1 = new ParentClass();
    obj1.parentMethod1(); //overriding private methods will give an error
    obj1.parentMethod2();

    ParentClass obj2 = new ChildClass();
    obj2.parentMethod2();
  }
}

Output:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The method parentMethod1() from the type ParentClass is not visible
at project1/com.techvidvan.methodoverriding.MethodOverridingDeno.main(MethodOverridingDeno.java:39)

To remove the exception comment this line:

obj1.parentMethod1();

After commenting the above line we will get an output as:

Inside the parentMethod2() of ParentClass
Inside the parentMethod1() of ChildClass

2. The methods declared as ‘final’ cannot be overridden

If we declare a method as final in the parent class then it can not be overridden in the subclass. It is used when we don’t want other classes to override the methods in the wrong way.

Code Snippet to illustrate overriding of a final method:

class Base
{
      	// final method can't be overridden
      	final void show()
      	{
      	}
}
class Base extends Derived
{
      	// This would produce an error
      	void show()
      	{
      	}
}

Output:

error: show() in Drived cannot override show() in Base
void show() { }
^

An overridden method is final

3. The methods declared as ‘static’ cannot be overridden

Method hiding is the process of defining the static method in the derived class with the same signature as a static method in the base class. That is when you override a static method of the superclass with the static keyword, then it will hide the method of the superclass. If a derived class redefines the static method of the base class, then it does not override that method but hides it.

The following table shows different scenarios when you define a method with the same signature as a method in a super-class.

Java Method Overriding Scenarios

Code to illustrate the overriding of a static method:

package com.techvidvan.methodoverriding;
//Parent Class
class Parent
{
static void method1()
{
    System.out.println("Inside static method1() of Parent class");
}
void method2()
{
    System.out.println("Inside non-static(instance) method2() of Parent class");
}
}
class Child extends Parent
{
//This will hide method1() of Child
static void method1()
{
    System.out.println("Inside static method1() of child class");
}
//This method overrides method2() in Parent
@Override
public void method2()
{
    System.out.println("Inside non-static(instance) method2() of child class");
}
}
//Driver class
public class MethodOverridingDemo
{
public static void main(String args[])
{
    Parent obj2 = new Child();
    obj2.method1();
    obj2.method2();
}
}

Output:

Inside static method1() of Parent class
Inside non-static(instance) method2() of child class

In the above code,

obj2.method1();

This statement should call method1 of child class but as the child class is overriding the method with the static keyword, therefore, this method will be hidden and the method1 of Parent class will be called.

4. Overriding Method must have the same return type (or subtype)

From Java 5.0 onwards, it is possible to have a different return type for an overridden method in the child class provided that the return type of child class be the same as a subtype of the overridden method’s return type of the base class. This type of return type is called a covariant return type.

Code to illustrate the above concept:

package com.techvidvan.methodoverriding;
//Parent Class
class Parent
{
  Parent display(String sentence)
  {
    System.out.println(sentence);
    return new Parent();
  }
}
//Child class
class Child extends Parent
{
  @Override
  Child display(String sentence)
  {
    System.out.println(sentence);
    return new Child();
  }
}
//Driver class
public class MethodOverridingDemo
{
  public static void main(String args[])
  {
    Parent obj = new Child();
    obj.display("TechVidvan's Java Tutorial");
    obj.display("Inside the method of the child class");
  }
}

Output:

TechVidvan’s Java Tutorial
Inside the method of the child class

5. Invoking Overridden Methods from child class

We can invoke or call the method of parent class while overriding the method in the derived class using the super keyword.

Code to illustrate the use of super keyword for calling overridden methods:

package com.techvidvan.methodoverriding;
//Parent Class
class Parent
{
  void display()
  {
    System.out.println("Inside display() of Parent class");
  }
}

//Child class
class Child extends Parent
{
  @Override
  void display()
  {

    //calling the parent class method through the super keyword
    super.display();

    System.out.println("Inside display() of child class");
  }
}

//Driver class
public class MethodOverridingDemo
{
  public static void main(String args[])
  {
    Parent obj = new Child();
    obj.display();
  }
}

Output:

Inside display() of Parent class
Inside display() of child class

6. Overriding Constructors

Constructors cannot be overridden that is the name of the constructors cannot be the same in parent and child class. Because the name of the constructor is always the same as the class name.

7. Overriding Abstract Methods

We can override Java Abstract methods only in the concrete classes, otherwise, a compile-time error will occur. A concrete class is a class that has the implementation of all of its methods. Simply, the classes that have no abstract methods are called concrete classes.

8. Overriding Methods from different packages

A subclass is present in a different package, then it can only override the non-final methods which are declared as public or protected.

9. Overriding and Exception-Handling in Java

There are two rules that we should remember while handling exceptions in Java:

Rule 1:

When a checked expression is thrown, it causes a compile-time error. If the superclass doesn’t throw any exception then the subclass can throw an error. The overriding method in the subclass can throw any unchecked (runtime) exception irrespective of whether the overridden method in the superclass declares the exception.

Code to explain Rule1:

package com.techvidvan.methodoverriding;
class Parent
{
  void display1()
  {
    System.out.println("Inside display1() method of Parent class");
  }
  void display2()
  {
    System.out.println("Inside display2() method of Parent class");
  }
}
class Child extends Parent
{
  @Override
  //no issue while throwing unchecked exception
  void display1() throws ArithmeticException
  {
    System.out.println("Inside display1() method of Child class");
  }
  @Override
  //compile-time error
  //issue while throwing checked exception
  void display2() throws Exception
  {
    System.out.println("Inside display2() method of Child class");
  }
}
//Driver class
public class MethodOverridingDemo
{
  public static void main(String args[])
  {
    Parent obj = new Child();
    obj.display1();
    obj.display2();
  }
}

Output:

Inside display1() method of Child class
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Exception Exception is not compatible with throws clause in Parent.display2()at project1/com.techvidvan.methodoverriding.Child.display2(MethodOverridingDemo.java:24)
at project1/com.techvidvan.methodoverriding1.MethodOverridingDemo.main(MethodOverridingDemo.java:36)

Rule 2:

A compile-time error occurs if an exception occurs in a parent class. The overriding methods of the child class should not throw any checked exceptions that are broader or newer to the exceptions declared by the overridden methods of the parent class.

For example, we can not override a method that declares an SQLException. Exception or any other non-runtime exception which is being overridden from a method that declares a FileNotFoundException, unless it is a subclass of FileNotFoundException.

Code to explain Rule2:

package com.techvidvan.methodoverriding;
//Parent Class
class Parent
{
  void display() throws RuntimeException
  {
    System.out.println("Inside display() method of Parent class");
  }
}
//Child class1
class Child1 extends Parent
{
  @Override
  // no issue while throwing same exception
  void display() throws RuntimeException

  {
    System.out.println("Inside display() method of Child1 class");
  }
}

class Child2 extends Parent
{
  @Override
  //no issue while throwing subclass exception
  void display() throws ArithmeticException
  {
    System.out.println("Inside display() method of Child2 class");
  }
}
class Child3 extends Parent
{
  @Override
  //no issue while not throwing any exception
  void display()
  {
    System.out.println("Inside display() method of Child3 class");
  }
}
class Child4 extends Parent
{
  @Override
  //compile-time error
  //issue while throwing parent exception
  void display() throws Exception
  {
    System.out.println("Inside display() method of Child4 class");
  }
}
//Driver class
public class MethodOverridingDemo
{
  public static void main(String args[])
  {
    Parent obj = new Child1();
    obj.display();

    obj = new Child2();
    obj.display();

    obj = new Child3();
    obj.display();

    obj = new Child4();
    obj.display();
  }
}

Output:

Inside display() method of Child1 class
Inside display() method of Child2 class
Inside display() method of Child3 class
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Exception Exception is not compatible with throws clause in Parent.display()
at project1/com.techvidvan.methodoverriding.Child4.display(MethodOverridingDemo.
java:45)
at project1/com.techvidvan.methodoverriding1.MethodOverridingDemo.main(MethodOverridingDemo.java:65)

10. Overriding a Synchronized/Strictfp Method

There is no effect on the overridden method if the method in the superclass is declared as synchronized or strictfp.

Method Overriding in Multilevel Inheritance in Java

package com.techvidvan.methodoverriding;
//Base Class
class Parent
{
void display()
{
  System.out.println("Inside display() method of Parent class");
}
}
//Inherited class
class Child extends Parent
{
//This method overrides show() of Parent
void display()
{
  System.out.println("Inside display() method of Child class");
}
}
//Inherited class
class GrandChild extends Child
{
//This method overrides show() of Parent
void display()
{
  System.out.println("Inside display() method of GrandChild class");
}
}
//Driver class
public class MethodOverridingDemo
{
  public static void main(String args[])
  {
    Parent obj1 = new GrandChild();
    obj1.display();
  }
}

Output:

Inside display() method of GrandChild class

When to Apply Method Overriding in Java

Method Overriding is when a class has several derived classes and the derived classes need to use the methods of their parent class with the same signature (number, type, and order of parameter), but with the different implementation. They can override the same method and add specific functionality without even disturbing the code of the parent class.

Example:

Example of Java Method Overriding

From the above diagram, the Employee class defines a getSalary() method, which is inherited by both classes Programmer and SalesPerson. But, the SalesPerson class modifies the method by adding a bonus.

Summary

From this article, we can conclude that the subclass can give its own specific implementation or definition to the method which it overrides, without even modifying its parent class. We covered the detailed description of the runtime polymorphism with the help of Method Overriding in Java. We also discussed various rules which should be kept in mind while using Method Overriding in Java.

Thank you for reading our article. Do share our article on Social Media.

Happy Learning 🙂

1 Response

  1. siara says:

    thank you for the great explanation.
    i took two years to understand this~~

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.