Method Overriding in Java

Declaring a method in sub class which is already present in parent class is known as method overriding. Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class. In this case the method in parent class is called overridden method and the method in child class is called overriding method. In this guide, we will see what is method overriding in Java and why we use it.

Usage of Java Method Overriding
  • Method overriding is used to provide specific implementation of a method that is already provided by its super class.

  • Method overriding is used for runtime polymorphism

Rules of method overriding in Java
  1. Argument list: The argument list of overriding method (method of child class) must match the Overridden method(the method of parent class). The data types of the arguments and their sequence should exactly match.

  2. Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class. For e.g. if the Access Modifier of parent class method is public then the overriding method (child class method ) cannot have private, protected and default Access modifier,because all of these three access modifiers are more restrictive than public.
    For e.g. This is not allowed as child class disp method is more restrictive(protected) than base class(public)

    class MyBaseClass{ public void disp() { System.out.println("Parent class method"); } } class MyChildClass extends MyBaseClass{ protected void disp(){ System.out.println("Child class method"); } public static void main( String args[]) { MyChildClass obj = new MyChildClass(); obj.disp(); } }

    Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot reduce the visibility of the inherited method from MyBaseClass
    However this is perfectly valid scenario as public is less restrictive than protected. Same access modifier is also a valid one.
    class MyBaseClass{ protected void disp() { System.out.println("Parent class method"); } } class MyChildClass extends MyBaseClass{ public void disp(){ System.out.println("Child class method"); } public static void main( String args[]) { MyChildClass obj = new MyChildClass(); obj.disp(); } }

    Child class method

  3. private, static and final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class.

  4. Overriding method (method of child class) can throw unchecked exceptions, regardless of whether the overridden method(method of parent class) throws any exception or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. We will discuss this in detail with example in the upcoming tutorial.

  5. Binding of overridden methods happen at runtime which is known as dynamic binding.

  6. If a class is extending an abstract class or implementing an interface then it has to override all the abstract methods unless the class itself is a abstract class.

Method Overriding Example

Lets take a simple example to understand this. We have two classes: A child class Boy and a parent class Human. The Boy class extends Human class. Both the classes have a common method void eat(). Boy class is giving its own implementation to the eat() method or in other words it is overriding the eat() method.

The purpose of Method Overriding is clear here. Child class wants to give its own implementation so that when it calls this method, it prints Boy is eating instead of Human is eating.

class Human{ //Overridden method public void eat() { System.out.println("Human is eating"); } } class Boy extends Human{ //Overriding method public void eat(){ System.out.println("Boy is eating"); } public static void main( String args[]) { Boy obj = new Boy(); //This will call the child class version of eat(); } }

Boy is eating
class Vehicle { void run(){System.out.println("Vehicle is running");} } class Bike extends Vehicle{ public static void main(String args[]){ Bike obj = new Bike();; } }

Output:Vehicle is running
Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.

class Vehicle{ void run(){System.out.println("Vehicle is running");} } class Bike2 extends Vehicle{ void run(){System.out.println("Bike is running safely");} public static void main(String args[]){ Bike2 obj = new Bike2();; }

Output:Bike is running safely
Advantage of method overriding

The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class code.

This is helpful when a class has several child classes, so if a child class needs to use the parent class method, it can use it and the other classes that want to have different implementation can use overriding feature to make changes without touching the parent class code.

Method Overriding and Dynamic Method Dispatch

Method Overriding is an example of runtime polymorphism. When a parent class reference points to the child class object then the call to the overridden method is determined at runtime, because during method call which method(parent class or child class) is to be executed is determined by the type of object. This process in which call to the overridden method is resolved at runtime is known as dynamic method dispatch. Lets see an example to understand this:

lass ABC{ //Overridden method public void disp() { System.out.println("disp() method of parent class"); } } class Demo extends ABC{ //Overriding method public void disp(){ System.out.println("disp() method of Child class"); } public void newMethod(){ System.out.println("new method of child class"); } public static void main( String args[]) { ABC obj = new ABC(); obj.disp(); ABC obj2 = new Demo(); obj2.disp(); } }

disp() method of parent class disp() method of Child class

In the above example the call to the disp() method using second object (obj2) is runtime polymorphism (or dynamic method dispatch).

Note: In dynamic method dispatch the object can call the overriding methods of child class and all the non-overridden methods of base class but it cannot call the methods which are newly declared in the child class. In the above example the object obj2 is calling the disp(). However if you try to call the newMethod() method (which has been newly declared in Demo class) using obj2 then you would give compilation error with the following message:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method xyz() is undefined for the type ABC
Real example of Java Method Overriding

Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.

Java method overriding example of bank
class Bank{ int getRateOfInterest(){return 0;} } class SBI extends Bank{ int getRateOfInterest(){return 8;} } class ICICI extends Bank{ int getRateOfInterest(){return 7;} } class AXIS extends Bank{ int getRateOfInterest(){return 9;} } class Test2{ public static void main(String args[]){ SBI s=new SBI(); ICICI i=new ICICI(); AXIS a=new AXIS(); System.out.println("SBI Rate of Interest: "+s.getRateOfInterest()); System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest()); System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest()); } }

SBI Rate of Interest: 8 ICICI Rate of Interest: 7 AXIS Rate of Interest: 9
Super keyword in Method Overriding

The super keyword is used for calling the parent class method/constructor. super.myMethod() calls the myMethod() method of base class while super() calls the constructor of base class. Let’s see the use of super in method Overriding.

As we know that we we override a method in child class, then call to the method using child class object calls the overridden method. By using super we can call the overridden method as shown in the example below:

class ABC{ public void myMethod() { System.out.println("Overridden method"); } } class Demo extends ABC{ public void myMethod(){ //This will call the myMethod() of parent class super.myMethod(); System.out.println("Overriding method"); } public static void main( String args[]) { Demo obj = new Demo(); obj.myMethod(); } }

Class ABC: mymethod() Class Test: mymethod()
Can we override static method?

No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.

Why we cannot override static method?

because static method is bound with class whereas instance method is bound with object. Static belongs to class area and instance belongs to heap area.

Can we override java main method?

No, because main is a static method.

Difference between method Overloading and Method Overriding in java

Overloading occurs when two or more methods in one class have the same method name but different parameters.

Overriding means having two methods with the same method name and parameters (i.e., method signature). One of the methods is in the parent class and the other is in the child class. Overriding allows a child class to provide a specific implementation of a method that is already provided its parent class.

Overriding vs. Overloading

Here are some important facts about Overriding and Overloading:

  1. The real object type in the run-time, not the reference variable's type, determines which overridden method is used at runtime. In contrast, reference type determines which overloaded method will be used at compile time.

  2. Polymorphism applies to overriding, not to overloading.

  3. Overriding is a run-time concept while overloading is a compile-time concept.

An Example of Overriding
class Dog{ public void bark(){ System.out.println("woof "); } } class Hound extends Dog{ public void sniff(){ System.out.println("sniff "); } public void bark(){ System.out.println("bowl"); } } public class OverridingTest{ public static void main(String [] args){ Dog dog = new Hound(); dog.bark(); } }


In the example above, the dog variable is declared to be a Dog. During compile time, the compiler checks if the Dog class has the bark() method. As long as the Dog class has the bark() method, the code compilers. At run-time, a Hound is created and assigned to dog. The JVM knows that dog is referring to the object of Hound, so it calls the bark() method of Hound. This is called Dynamic Polymorphism.

An Example of Overloading
class Dog { public void bark() { System.out.println("woof "); } //overloading method public void bark(int num){ for(int i=0; i<num; i++) System.out.println("woof "); } }

In this overloading example, the two bark method can be invoked by using different parameters. Compiler know they are different because they have different method signature (method name and method parameter list).

More topics on Method Overriding
  • Access Modifiers in java

  • Instagram