Open In App

Overriding in Java

Last Updated : 03 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Overriding in Java occurs when a subclass implements a method which is already defined in the superclass or Base Class. The method in the subclass must have the same signature as in the superclass. It allows the subclass to modify the inherited methods.

Example: Below is an example of how overriding works in Java.

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.

Explnation: The Animal class defines base functionalities like move() and eat().t he 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: Below is the implementation of the Java Method Overriding

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.

Rules for Java Method Overriding

1. The Overriding and Access Modifiers

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: Java program to demonstrate Overriding an Access-Modifiers

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()

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

2. Override methods can not be overridden

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

Example: Java program which shows the final method can not override.

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 Overriding vs 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: Java program to show method hiding in Java.

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() 

4. Private methods can not 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 shows private method can not be overridden in java

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: Java Program which shows Covariant Return Type in Method Overriding.

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. showsInvoking overridden method from sub-class

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

Example: This example shows we can parent’s overridden method using super an.

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).

Overriding and Exception-Handling

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: Java program to 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.

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

1. Overloading is about the same method having different signatures. Overriding is about the same method, and same signature but different classes connected through inheritance. 

Method Overloading vs Method Overriding

2. Overloading is an example of compiler-time polymorphism and overriding is an example of run-time polymorphism.

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


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg
  翻译: