The Wayback Machine - https://web.archive.org/web/20250402205846/https://www.geeksforgeeks.org/overriding-in-java/
Open In App

Overriding in Java

Last Updated : 28 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Overriding in Java occurs when a subclass (child class) implements a method that is already defined in the superclass or Base Class. The overriding method must have the same name, parameters, and return type as the method in the parent class. This allows subclasses to modify inherited behavior while maintaining a consistent interface.

  • The method in the subclass must have the same name, return type, and parameters as the method in the superclass.
  • The method called is determined at runtime, allowing dynamic behavior based on the object’s type.
  • Only non-static methods can be overridden.
  • The@Override annotation ensures the method is correctly overridden and helps avoid errors.

Example: This example demonstrates method overriding in Java, where the move() method in the Dog class overrides the move() method in the Animal class, while other methods like eat() are inherited from the superclass.

Java
// Example of Overriding in Java
class Animal {
    // Base class
    void move() { System.out.println(
      "Animal is moving."); }
    void eat() { System.out.println(
      "Animal is eating."); }
}

class Dog extends Animal {
    @Override void move()
    { // move method from Base class is overriden in this
      // method
        System.out.println("Dog is running.");
    }
    void bark() { System.out.println("Dog is barking."); }
}

public class Geeks {
    public static void main(String[] args)
    {
        Dog d = new Dog();
        d.move(); // Output: Dog is running.
        d.eat(); // Output: Animal is eating.
        d.bark(); // Output: Dog is barking.
    }
}

Output
Dog is running.
Animal is eating.
Dog is barking.

Explanation: The Animal class defines base functionalities like move() and eat(). The Dog class inherits from Animal and overrides the move() method to provide a specific behavior Dog is running. Both classes can access their own methods. When creating a Dog object, calling move() executes the overridden method.


Method Overriding in Java

Method overriding is a key concept in Java that enables Run-time polymorphism. It allows a subclass to provide its specific implementation for a method inherited from its parent class. The actual method executed is determined by the object’s runtime type, not just the reference variable’s type. This dynamic behaviour is crucial for creating flexible and extensible object-oriented designs.

Example: This example demonstrates runtime polymorphism in Java, where the show() method is overridden in the Child class, and the method called depends on the object type at runtime.

Java
// Java program to demonstrate
// method overriding in java
class Parent {
    // base class or superclass which is going to overriden
    // below
    void show() { System.out.println("Parent's show()"); }
}
// Inherited class
class Child extends Parent {
    // This method overrides show() of Parent
    @Override void show()
    {
        System.out.println("Child's show()");
    }
}
// Driver class
class Geeks {
    public static void main(String[] args)
    {
        // If a Parent type reference refers
        // to a Parent object, then Parent's
        // show is called
        Parent obj1 = new Parent();
        obj1.show();

        // If a Parent type reference refers
        // to a Child object Child's show()
        // is called. This is called RUN TIME
        // POLYMORPHISM.
        Parent obj2 = new Child();
        obj2.show();
    }
}

Output
Parent's show()
Child's show()

Explanation: in this code the Child class inherits from the Parent class and overrides the show() method, providing its own implementation. When a Parent reference points to a Child object, the Child’s overridden show() method is executed at runtime, showcasing the principle of polymorphism in Java.

Why to Use Overriding?

The key reasons to use method overriding in Java are listed below:

  • Achieve Polymorphism: Allows different behaviors for the same method at runtime based on the object type.
  • Extend or Modify Behavior: Enables subclass to modify or extend the functionality of the superclass method.
  • Dynamic Method Dispatch: Supports dynamic method dispatch, where the method to be executed is determined at runtime.
  • Enhance Readability: Improves code readability by providing specific implementations while maintaining a consistent method name.

Rules for Java Method Overriding

1. Access Modifiers in overriding

An overriding method’s access modifier in a subclass can be more permissive (e.g., protected to the public) than the overridden method in the superclass. However, reducing the access level (e.g., making a protected method private) is not allowed and will result in a compile-time error.

Example: This example demonstrates method overriding with access modifiers, showing how a method can be overridden with a more accessible modifier, but private methods cannot be overridden.

Java
// A Simple Java program to demonstrate
// Overriding and Access-Modifiers
class Parent {
    // private methods are not overridden
    private void m1()
    {
        System.out.println("From parent m1()");
    }

    protected void m2()
    {
        System.out.println("From parent m2()");
    }
}

class Child extends Parent {
    // new m1() method
    // unique to Child class
    private void m1()
    {
        System.out.println("From child m1()");
    }

    // overriding method
    // with more accessibility
    @Override public void m2()
    {
        System.out.println("From child m2()");
    }
}

class Geeks {
    public static void main(String[] args)
    {
        // parent class object
        Parent P = new Parent();
        P.m2();
        // child class object
        Parent C = new Child();
        C.m2();
    }
}

Output
From parent m2()
From child m2()

Explanation: Here the parent class is overridden by the subclass and from the output we can easily identify the difference.

2. Final Methods Cannot Be Overriden

If we don’t want a method to be overridden, we declare it as final. Please see Using Final with Inheritance. 

Note: If a method is declared as final, subclasses cannot override it.

Example: This example demonstrates that final methods in Java cannot be overridden in subclasses.

Java
// A Java program to demonstrate that
// final methods cannot be overridden

class Parent {
    // Can't be overridden
    final void show() {}
}

class Child extends Parent {
    // This would produce error
    void show() {}
}


Output:

MethodOverriding

3. Static methods can not be overridden(Method Hiding)

When you define a static method with the same signature as a static method in the base class, it is known as method hiding.

  • Subclass Instance method can override the superclass’s Instance method but when we try to override the superclass static method gives a compile time error.
  • Subclass Static Method generate compile time when trying to override superclass Instance method subclass static method hides when trying to override superclass static method.

Example: This example demonstrates method hiding for static methods in Java, where a static method in the subclass hides the static method in the superclass, while non-static methods can be overridden.

Java
// Java program to show that
// if the static method is redefined by a derived
// class, then it is not overriding, it is hiding
class Parent {
    // Static method in base class
    // which will be hidden in subclass
    static void m1()
    {
        System.out.println("From parent "
                           + "static m1()");
    }
    // Non-static method which will
    // be overridden in derived class
    void m2()
    {
        System.out.println(
            "From parent "
            + "non - static(instance) m2() ");
    }
}

class Child extends Parent {
    // This method hides m1() in Parent
    static void m1()
    {
        System.out.println("From child static m1()");
    }

    // This method overrides m2() in Parent
    @Override public void m2()
    {
        System.out.println(
            "From child "
            + "non - static(instance) m2() ");
    }
}

// Driver class
class Geeks {
    public static void main(String[] args)
    {
        Parent obj1 = new Child();

        // here parents m1 called.
        // bcs static method can not overriden
        obj1.m1();

        // Here overriding works
        // and Child's m2() is called
        obj1.m2();
    }
}

Output
From parent static m1()
From child non - static(instance) m2() 

Note: When a subclass defines a static method with the same signature as the parent’s static method, it hides the parent method. The method called depends on the reference type, not the object type.

4. Private Methods Cannot Be Overridden

Private methods cannot be overridden as they are bonded during compile time. Therefore we can’t even override private methods in a subclass.

Example: This example demonstrates method hiding for private methods in Java, where a private method in the subclass does not override the private method in the superclass, and the subclass’s public method overrides the superclass’s public method.

Java
class SuperClass {
    private void privateMethod()
    {
        System.out.println(
            "it is a private method in SuperClass");
    }

    public void publicMethod()
    {
        System.out.println(
            "it is a public method in SuperClass");
        privateMethod();
    }
}

class SubClass extends SuperClass {
    // This is a new method with the same name as the
    // private method in SuperClass
    private void privateMethod()
    {
        System.out.println(
            "it is private method in SubClass");
    }

    // This method overrides the public method in SuperClass
    public void publicMethod()
    {
        // calls the private method in
        // SubClass, not SuperClass
        System.out.println(
            "it is a public method in SubClass");
        privateMethod();
    }
}

public class Geeks {
    public static void main(String[] args)
    {
        SuperClass o1 = new SuperClass();
        // calls the public method in
        // SuperClass
        o1.publicMethod();
        SubClass o2 = new SubClass();
        // calls the overridden public
        // method in SubClass
        o2.publicMethod();
    }
}

Output
it is a public method in SuperClass
it is a private method in SuperClass
it is a public method in SubClass
it is private method in SubClass

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

From Java 5.0 onwards it is possible to have different return types for an overriding method in the child class, but the child’s return type should be a sub-type of the parent’s return type. This phenomenon is known as the covariant return type.

Example: This example demonstrates covariant return types in Java, where the subclass method overrides the superclass method with a more specific return type.

Java
class SuperClass {
    public Object method()
    {
        System.out.println(
            "This is the method in SuperClass");
        return new Object(); 
    }
}

class SubClass extends SuperClass {
    public String method()
    {
        System.out.println(
            "This is the method in SubClass");
        return "Hello, World!";
      // having the Covariant return type
    }
}

public class Geeks {
    public static void main(String[] args)
    {
        SuperClass obj1 = new SuperClass();
        obj1.method();

        SubClass obj2 = new SubClass();
        obj2.method();
    }
}

Output
This is the method in SuperClass
This is the method in SubClass

6. Invoking Parent’s Overridden Method Using super

We can call the parent class method in the overriding method using the super keyword. 

Note: Use super.methodName() to call the parent’s version

Example: This example demonstrates calling the overridden method from the subclass using super to invoke the superclass method in Java.

Java
// A Java program to demonstrate that overridden
// method can be called from sub-class
// Base Class
class Parent {
    void show() { System.out.println("Parent's show()"); }
}

// Inherited class
class Child extends Parent {
    // This method overrides show() of Parent
    @Override void show()
    {
        super.show();
        System.out.println("Child's show()");
    }
}

// Driver class
class Geeks{
    public static void main(String[] args)
    {
        Parent o = new Child();
        o.show();
    }
}

Output
Parent's show()
Child's show()

Overriding and Constructor

We can not override the constructor as the parent and child class can never have a constructor with the same name(The constructor name must always be the same as the Class name).

Exception-Handling in Overriding

Below are two rules to note when overriding methods related to exception handling.

Rule 1: If the super-class overridden method does not throw an exception, the subclass overriding method can only throw the unchecked exception, throwing a checked exception will lead to a compile-time error. 

Example: Below is an example of a java program when the parent class method does not declare the exception

Java
// Java program to demonstrate overriding when
// superclass method does not declare an exception

class Parent {
    void m1() { System.out.println("From parent m1()"); }

    void m2() { System.out.println("From parent  m2()"); }
}

class Child extends Parent {
    @Override
    // no issue while throwing unchecked exception
    void m1() throws ArithmeticException
    {
        System.out.println("From child m1()");
    }

    @Override
    // compile-time error
    // issue while throwing checked exception
    void m2() throws Exception
    {
        System.out.println("From child m2");
    }
}


Output

OverrideExc

Explanation: This example shows that uper-class overridden method does not throw an exception, the subclass overriding method can only throw the exception because the super class does not declare the exception.

Rule 2: If the superclass overridden method does throw an exception, the subclass overriding method can only throw the same, subclass exception. Throwing parent exceptions in the Exception hierarchy will lead to compile time error. Also, there is no issue if the subclass overridden method does not throw any exception. 

Example: This example demonstrate overriding when superclass method does declare an exception

Java
class Parent {
    void m1() throws RuntimeException
    {
        System.out.println("From parent m1()");
    }
}

class Child1 extends Parent {
    @Override void m1() throws RuntimeException
    {
        System.out.println("From child1 m1()");
    }
}

class Child2 extends Parent {
    @Override void m1() throws ArithmeticException
    {
        System.out.println("From child2 m1()");
    }
}

class Child3 extends Parent {
    @Override void m1()
    {
        System.out.println("From child3 m1()");
    }
}

class Child4 extends Parent {
    @Override void m1() throws Exception
    {
        // This will cause a compile-time error due to the
        // parent class method not declaring Exception
        System.out.println("From child4 m1()");
    }
}

public class MethodOverridingExample {
    public static void main(String[] args)
    {
        Parent p1 = new Child1();
        Parent p2 = new Child2();
        Parent p3 = new Child3();
        Parent p4 = new Child4();

        // Handling runtime exceptions for each child class
        // method
        try {
            p1.m1();
        }
        catch (RuntimeException e) {
            System.out.println("Exception caught: " + e);
        }

        try {
            p2.m1();
        }
        catch (RuntimeException e) {
            System.out.println("Exception caught: " + e);
        }

        try {
            p3.m1();
        }
        catch (Exception e) {
            System.out.println("Exception caught: " + e);
        }

        // Child4 throws a compile-time error due to
        // mismatched exception type
        try {
            p4.m1(); // This will throw a compile-time error
        }
        catch (Exception e) {
            System.out.println("Exception caught: " + e);
        }
    }
}


Output

ExceptionOverriding3


Overriding and Abstract Method

Abstract methods in an interface or abstract class are meant to be overridden in derived concrete classes otherwise a compile-time error will be thrown.

Overriding and Synchronized/strictfp Method

The presence of a synchronized/strictfp modifier with the method has no effect on the rules of overriding, i.e. it’s possible that a synchronized/strictfp method can override a non-synchronized/strictfp one and vice-versa.

Example: This example demonstrates multi-level method overriding in Java, where a method is overridden across multiple levels of inheritance, and the method called is determined at runtime.

Java
// A Java program to demonstrate
// multi-level overriding
// Base Class
class Parent {
    void show() { System.out.println("Parent's show()"); }
}

// Inherited class
class Child extends Parent {
    // This method overrides show() of Parent
    void show() { System.out.println("Child's show()"); }
}

// Inherited class
class GrandChild extends Child {
    // This method overrides show() of Parent
    void show()
    {
        System.out.println("GrandChild's show()");
    }
}

// Driver class
class Geeks {
    public static void main(String[] args)
    {
        Parent o = new GrandChild();
        o.show();
    }
}

Output
GrandChild's show()

Method Overriding vs Method Overloading

This image demonstrates the difference between method overloading (same method name but different parameters in the same class) and overriding (same method signature in a subclass, replacing the superclass method).


Method Overloading vs Method Overriding

The table below demonstrates the difference between Method Overriding and Method Overloading

Features

Method Overriding

Method Overloading

Definition

Method overriding is about the same signature in subclass.

Method overloading is about same method name, different parameters.

Polymorphism

It is also known as Runtime polymorphism

It is also known as Compiletime polymorphism

Inheritance

Requires inheritance.

Can be in the same class or subclass

Return Type

Return type must be same

Return type can be different

Exceptions

Must follow overriding rules.

No restrictions.

Method Overriding In Java-FAQs

Q1. What is Method Overriding?

Overridden methods enable Java’s run-time polymorphism, allowing subclasses to provide specific implementations of methods defined in a parent class. This supports the “one interface, multiple methods” concept of polymorphism. Dynamic Method Dispatch is a key feature, enabling code libraries to call methods on new class instances without recompiling, while maintaining a clean, abstract interface. It allows calling methods from derived classes without knowing their specific type. 

Q2. When to apply Method Overriding? (with example)

Overriding and inheritance work together to apply polymorphism by organizing superclasses and subclasses in a hierarchy, from general to specialized. The superclass provides common methods for subclasses to use or override, ensuring flexibility while maintaining a consistent interface. For example, in an employee management system, the base class Employee defines methods like raiseSalary(), transfer(), and promote(). Subclasses such as Manager or Engineer can override these methods with their own logic. This allows us to pass a list of employees, call methods like raiseSalary(), and let each employee type execute its own implementation without knowing the specific type of employee. 

Java Overriding

 

Java
// Java program to demonstrate application
// of overriding in Java
// Base Class
class Employee {
    public static int base = 10000;
    int salary() { return base; }
}

// Inherited class
class Manager extends Employee {
    // This method overrides salary() of Parent
    int salary() { return base + 20000; }
}

// Inherited class
class Clerk extends Employee {
    // This method overrides salary() of Parent
    int salary() { return base + 10000; }
}

// Driver class
class Main {
    // This method can be used to print the salary of
    // any type of employee using base class reference
    static void printSalary(Employee e)
    {
        System.out.println(e.salary());
    }

    public static void main(String[] args)
    {
        Employee obj1 = new Manager();

        // We could also get type of employee using
        // one more overridden method.loke getType()
        System.out.print("Manager's salary : ");
        printSalary(obj1);

        Employee obj2 = new Clerk();
        System.out.print("Clerk's salary : ");
        printSalary(obj2);
    }
}

Output
Manager's salary : 30000
Clerk's salary : 20000

Q3. Why is method overriding used?

Method overriding is used because of the following reasons:

  • To achieve runtime polymorphism.
  • To modify inherited behavior in subclasses.
  • To enforce method contracts (e.g., interface methods).
  • To support dynamic method dispatch.

Q4. Can we override a static method in Java?

No, static methods cannot be overridden. Instead, they are hidden if a subclass defines a static method with the same signature.

Q5. What happens if we don’t use @Override annotation?

The method will still override if the signature matches. But using @Override helps detect mistakes




Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg