Java – Method Overriding

A subclass changing the behavior of a method it inherited from its super class is called as Method Overriding.

While overriding a method, a subclass must define it with the same set of method parameters and return type as present in its super class.

package com.techstackjournal.methodoverriding;

public class Shape {

	public void draw(int thickness) {
		System.out.println("Preparing the canvas...");
	}

}
package com.techstackjournal.methodoverriding;

public class Rectangle extends Shape {

	public void draw(int thickness) {
		System.out.println("Drawing Rectangle...");
	}

	public void draw(int thickness, String fillColor) {
		System.out.println("Drawing Rectangle and Filling Color...");
	}

}
package com.techstackjournal.methodoverriding;

public class Application {

	public static void main(String[] args) {

		Rectangle rectangle = new Rectangle();

		rectangle.draw(1);

	}

}
Drawing Rectangle...
  • Here, we are overriding draw method of Shape class in Rectangle class by implementing it again in Rectangle class
  • Calling the draw method using Rectangle reference variable invokes draw method of Rectangle class

Advantages of Method Overriding:

  • Method overriding will allow the subclass to define the method that is specific to the subclass
  • By overriding a method instead of creating a new method a subclass can get benefits of Polymorphism

Points to Remember

Rules of Method Overriding:

  • A subclass must maintain the same set of method arguments and return type
  • If the return type is a class, then the return type can be a sub class of super class return type
  • A subclass cannot reduce the visibility of the inherited method from super class. That means, overriding a public method in super class as a private method in subclass is not legal
  • A subclass can override a method only when that method is visible to it.
  • If a subclass define a method with the same signature as of super class which has defined it as private, we do not call it as overriding.
  • You can increase the visibility of an inherited method from super class. That means, a protected method in super class can be defined as a public method in subclass.
  • A subclass cannot override a final method
  • A subclass cannot override a static method
  • Some additional rules related to exceptions, which we will see in later sections
    • A subclass cannot throw a broader exception than what is declared in the super class
    • But it can throw a narrower exception
    • Overriding method can throw any runtime exception, even if it is not defined in its declaration in super class