DEV Community

PRIYA K
PRIYA K

Posted on • Edited on

Method Overriding in Java

Overriding in Java - GeeksforGeeks

Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.

favicon geeksforgeeks.org


https://www.w3schools.in/java/method-overriding
https://www.tutorialspoint.com/java/java_overriding.htm
https://docs.oracle.com/javase/tutorial/java/IandI/override.html

Method Overloading vs Method Overriding in Java – What's the Difference?

By Mikael Lassa In Java, method overloading and method overriding both refer to creating different methods that share the same name. While the two concepts share some similarities, they are distinct notions with markedly different use cases. Having ...

favicon freecodecamp.org

occurs when a subclass provides a specific implementation for a method that is already defined in its superclass or parent class
It is a concept of Object-Oriented Programming (OOP) used to achieve runtime polymorphism.
the method executed is determined by the actual object type at runtime, not the reference type.
The overridden method in the subclass must have the same name, parameters,data type and return type as the method in the parent class.
Instance methods can be overridden if they are inherited by the subclass

Declaring a method in the subclass which already exists there in the parent class is known as method overriding. When a class is inheriting a method from a superclass of its own, then there is an option of overriding the method provided it is not declared as final. The advantage of using overriding is the ability to classify a behavior that's specific to the child class, and the child class can implement a parent class method based on its necessity.

. If a class inherits a method from its superclass, then there is a chance to override the method provided that it is not marked final.

There are certain rules that a programmer should follow to implement overriding. These are:
In Java, a method can only be written in the child class and not in same class.
Argument list should be the same as that of the overridden method of that class.
Instance methods can also be overridden if they are inherited by the child class.
A constructor cannot be overridden.
Final - declared methods cannot be overridden.
Any method that is static cannot be used to override.
The return type must have to be the same, or a subtype of the return type declared in the original overridden method in the parent class.
If a method cannot be inherited, then it cannot be overridden.
A child class within the same package as the instance's parent class can override any parent class method that is not declared private or final.
A child class in a different package can only override the non-final methods declared as public or protected.

*Before Method Overriding,Learn Inheritance *
Inheritance is an OOP property that allows us to derive a new class (subclass) from an existing class (superclass). The subclass inherits the attributes and methods of the superclass.
if the same method is defined in both the superclass and the subclass, then the method of the subclass class overrides the method of the superclass. This is known as method overriding.

The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which means a subclass can implement a parent class method based on its requirement.

In object-oriented terms, overriding means to override the functionality of an existing method.

Example : Method Overriding

class Animal {
   public void displayInfo() {
      System.out.println("I am an animal.");
   }
}

class Dog extends Animal {
   @Override
   public void displayInfo() {
      System.out.println("I am a dog.");
   }
}

class Main {
   public static void main(String[] args) {
      Dog d1 = new Dog();
      d1.displayInfo();
   }
}
Enter fullscreen mode Exit fullscreen mode

Output:
I am a dog.

Explanation
the displayInfo() method is present in both the Animal superclass and the Dog subclass.

When we call displayInfo() using the d1 object (object of the subclass), the method inside the subclass Dog is called. The displayInfo() method of the subclass overrides the same method of the superclass.

The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.

Java Method Overriding
Method overriding allows us to achieve run-time polymorphism and is used for writing specific definitions of a subclass method that is already defined in the superclass.

The method is superclass and overridden method in the subclass should have the same declaration signature such as parameters list, type, and return type.

Usage of Java Method Overriding
Following are the two important usages of method overriding in Java:
Method overriding is used for achieving run-time polymorphism.
Method overriding is used for writing specific definition of a subclass method (this method is known as the overridden method).

Key Rules for Overriding

  • To override a method in Java, the child method must have the same name, parameters, and return type as the parent method.
  • Declaring a method in sub class which is already present in parent class is known as method overriding.
  • The method in parent class is called overridden method and the method in child class is called overriding method.
  • Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class.
  • It requires an "IS-A" relationship (inheritance), and the overriding method cannot be more restrictive in access than the original.
  • final, static, and private methods cannot be overridden, and constructors are not overridden.

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.

The argument list should be exactly the same as that of the overridden method.

The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.

The access level cannot be more restrictive than the overridden method's access level. For example: If the superclass method is declared public then the overridding method in the sub class cannot be either private or protected.

  • Instance methods can be overridden only if they are inherited by the subclass.
  • A method declared final cannot be overridden.
  • A method declared static cannot be overridden but can be re-declared.
  • If a method cannot be inherited, then it cannot be overridden.
  • A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
  • A subclass in a different package can only override the non-final methods declared public or protected.
  • An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.
  • Constructors cannot be overridden

Java Method and Constructor Overriding
In Java, each class has a different name and the constructor's name is the same as the class name. Thus, we cannot override a constructor as they cannot have the same name.

Java Method Overriding: Using the super Keyword
When invoking a superclass version of an overridden method the super keyword is used.

Example: Using the super Keyword

class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}
class Dog extends Animal {
   public void move() {
      super.move();   // invokes the super class method
      System.out.println("Dogs can walk and run");
   }
}
public class TestDog {
   public static void main(String args[]) {
      Animal b = new Dog();   // Animal reference but Dog object
      b.move();   // runs the method in Dog class
   }
}
Enter fullscreen mode Exit fullscreen mode

Output
Animals can move
Dogs can walk and run

Cannot reduce access
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)
However this is perfectly valid scenario as public is less restrictive than protected. Same access modifier is also a valid one.

The parameter list must not change: the overriding method must take the same number and type of parameters as the overridden method – otherwise, you would just be overloading the method.
The return type must not change (Note: if the method returns an object, a subclass of that object is allowed as the return type).
The access modifier must be either the same or a less restrictive one (for example, if the overridden method is protected, you can declare the overriding method as public, but not private).
Thrown checked exceptions, if any, can be removed or reduced by the overriding method. This means that the overriding method can throw the same checked exception as the overridden method, or a subclass of that checked exception, but not a broader exception. This restriction does not apply to unchecked exceptions.
Enter fullscreen mode Exit fullscreen mode

There are several rules for methods of subclasses which should override methods of a superclass:
the method must have the same name as in the superclass;
the arguments should be exactly the same as in the superclass method;
the return type should be the same type or a subtype of the return type declared in the method of the superclass;
the access level must be the same or more open than the overridden method's access level;
a private method cannot be overridden because it's not inherited by subclasses;
if the superclass and its subclass are in the same package, then package-private methods can be overridden;
static methods cannot be overridden.

To verify these rules, there is a special annotation @override. It allows you to know whether a method will actually be overridden or not, which can be helpful if you have any question about the method's behavior. If for some reason, the compiler decides that the method cannot be overridden, it will generate a compiler error. But remember that this annotation is not required, it's only for convenience.

Output
Exception in thread "main" java.lang.Error: Unresolved compilation
problem: Cannot reduce the visibility of the inherited method from MyBaseClass

  • Using the @override annotation is recommended to trigger compiler checks, and the super keyword can be used to call the base method.
  • The @override annotation catches mistakes like typos in method names In Java, annotations are the metadata that we used to provide information to the compiler. Here, the @override annotation specifies the compiler that the method after this annotation overrides the method of the superclass.

While not compulsory, it is good practice to use the @override annotation when overriding a method: this annotation will check that the method is being overridden correctly, and will warn you if that's not the case.

It is not mandatory to use @override. However, when we use this, the method should follow all the rules of overriding. Otherwise, the compiler will generate an error.....to be discussed

Java picks which method to run at run time, based on the actual object type, not just the reference variable type.
Enter fullscreen mode Exit fullscreen mode

private, static and final methods cannot be overridden as they are local to the class.
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.
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.
Binding of overridden methods happen at runtime which is known as dynamic binding.
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.

We should always override abstract methods of the superclass

Special Cases in Overriding
1. Calling Parent Method Using super
The super keyword can invoke the parent class method from the overriding method.

2. Final Methods Cannot Be Overridden
If we don't want a method to be overridden, we declare it as final. Please see Using Final with Inheritance.

3. Static Methods
Static methods cannot be overridden; defining a static method in a subclass with the same signature as in the superclass hides the superclass method.
Instance methods can be overridden, but a subclass cannot override a superclass static method.
A static method in a subclass with the same signature as a superclass static method hides the original method.

4. Private Methods
Private methods cannot be overridden because they are not visible to subclasses.
A subclass method with the same name is treated as a new, independent method, unrelated to the parent class.

5. Covariant Return Types
In method overriding, the return type of the overriding method can be a subclass of the return type of the overridden method.
This feature is known as covariant return type and allows more specific return types in the subclass.

Why Do We Use Method Overriding?
To change or enhance the behavior of an existing method in a subclass.
To achieve runtime polymorphism — method calls depend on the actual object type.
To reuse method names logically, reducing redundancy.

Advantage of method overriding
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

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.

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.

we override a method in child class, then call to the method using child class object calls the overridden method.

Can we access the method of the superclass after overriding?
the answer is Yes.
To access the method of the superclass from the subclass, we use the super keyword.

Example : Use of super Keyword

class Animal {
   public void displayInfo() {
      System.out.println("I am an animal.");
   }
}

class Dog extends Animal {
   public void displayInfo() {
      super.displayInfo();
      System.out.println("I am a dog.");
   }
}

class Main {
   public static void main(String[] args) {
      Dog d1 = new Dog();
      d1.displayInfo();
   }
}

Enter fullscreen mode Exit fullscreen mode

Output:
I am an animal.
I am a dog.

the subclass Dog overrides the method displayInfo() of the superclass Animal.
When we call the method displayInfo() using the d1 object of the Dog subclass, the method inside the Dog subclass is called; the method inside the superclass is not called.
Inside displayInfo() of the Dog subclass, we have used super.displayInfo() to call displayInfo() of the superclass.

It is important to note that constructors in Java are not inherited. Hence, there is no such thing as constructor overriding in Java.

However, we can call the constructor of the superclass from its subclasses. For that, we use super().

Access Specifiers in Method Overriding
The same method declared in the superclass and its subclasses can have different access specifiers. However, there is a restriction.
We can only use those access specifiers in subclasses that provide larger access than the access specifier of the superclass. For example,
Suppose, a method myClass() in the superclass is declared protected. Then, the same method myClass() in the subclass can be either public or protected, but not private.

Example : Access Specifier in Overriding

class Animal {
   protected void displayInfo() {
      System.out.println("I am an animal.");
   }
}

class Dog extends Animal {
   public void displayInfo() {
      System.out.println("I am a dog.");
   }
}

class Main {
   public static void main(String[] args) {
      Dog d1 = new Dog();
      d1.displayInfo();
   }
}
Enter fullscreen mode Exit fullscreen mode

Output:
I am a dog.

Explanation
the subclass Dog overrides the method displayInfo() of the superclass Animal.
Whenever we call displayInfo() using the d1 (object of the subclass), the method inside the subclass is called.
Notice that, the displayInfo() is declared protected in the Animal superclass. The same method has the public access specifier in the Dog subclass. This is possible because the public provides larger access than the protected.

Overriding Abstract Methods
In Java, abstract classes are created to be the superclass of other classes. And, if a class contains an abstract method, it is mandatory to override it.

method overloading and method overriding
In Java, method overloading and method overriding both refer to creating different methods that share the same name.
What is Method Overloading in Java?
means creating a different method with the same name in the same class, but with a different parameter list.
A method can also be overloaded by changing the number of parameters.

Key Rules of Method Overloading

The overloaded and overloading methods must be in the same class (Note: this includes any methods inherited, even implicitly, from a superclass).
The method parameters must change: either the number or the type of parameters must be different in the two methods.
The return type can be freely modified.
The access modifier (public, private, and so on) can be freely modified.
Thrown exceptions, if any, can be freely modified.
Enter fullscreen mode Exit fullscreen mode

Forbidding overriding
forbid overriding of a method, declare it with the final keyword.

public final void method() {
    // do something
}
Enter fullscreen mode Exit fullscreen mode

if you try to override this method in a subclass, a compile-time error will occur.

Overriding and overloading methods together
that overloading is a feature that allows a class to have more than one method with the same name, if their arguments are different.

We can also override and overload an instance method in a subclass at the same time. Overloaded methods do not override superclass instance methods. They are new methods, unique to the subclass.

Overriding and Hiding Methods
Instance Methods

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This subtype is called a covariant return type.

When overriding a method, you might want to use the @override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error. For more information on @override, see Annotations.

Static Methods

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.

The distinction between hiding a static method and overriding an instance method has important implications:

The version of the overridden instance method that gets invoked is the one in the subclass.
The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
Enter fullscreen mode Exit fullscreen mode

Consider an example that contains two classes. The first is Animal, which contains one instance method and one static method:

public class Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Animal");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Animal");
    }
}
Enter fullscreen mode Exit fullscreen mode

The second class, a subclass of Animal, is called Cat:

public class Cat extends Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Cat");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Cat");
    }
    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = myCat;
        Animal.testClassMethod();
        myAnimal.testInstanceMethod();
    }
}
Enter fullscreen mode Exit fullscreen mode

The Cat class overrides the instance method in Animal and hides the static method in Animal. The main method in this class creates an instance of Cat and invokes testClassMethod() on the class and testInstanceMethod() on the instance.

The output from this program is as follows:
The static method in Animal
The instance method in Cat

As promised, the version of the hidden static method that gets invoked is the one in the superclass, and the version of the overridden instance method that gets invoked is the one in the subclass.

Interface Methods
Default methods and abstract methods in interfaces are inherited like instance methods. However, when the supertypes of a class or interface provide multiple default methods with the same signature, the Java compiler follows inheritance rules to resolve the name conflict. These rules are driven by the following two principles:

Instance methods are preferred over interface default methods.

Consider the following classes and interfaces:
Enter fullscreen mode Exit fullscreen mode
public class Horse {
        public String identifyMyself() {
            return "I am a horse.";
        }
    }
    public interface Flyer {
        default public String identifyMyself() {
            return "I am able to fly.";
        }
    }
    public interface Mythical {
        default public String identifyMyself() {
            return "I am a mythical creature.";
        }
    }
    public class Pegasus extends Horse implements Flyer, Mythical {
        public static void main(String... args) {
            Pegasus myApp = new Pegasus();
            System.out.println(myApp.identifyMyself());
        }
    }

Enter fullscreen mode Exit fullscreen mode
The method Pegasus.identifyMyself returns the string I am a horse.
Methods that are already overridden by other candidates are ignored. This circumstance can arise when supertypes share a common ancestor.

Consider the following interfaces and classes:
Enter fullscreen mode Exit fullscreen mode
    public interface Animal {
        default public String identifyMyself() {
            return "I am an animal.";
        }
    }
    public interface EggLayer extends Animal {
        default public String identifyMyself() {
            return "I am able to lay eggs.";
        }
    }
    public interface FireBreather extends Animal { }
    public class Dragon implements EggLayer, FireBreather {
        public static void main (String... args) {
            Dragon myApp = new Dragon();
            System.out.println(myApp.identifyMyself());
        }
    }
Enter fullscreen mode Exit fullscreen mode
The method Dragon.identifyMyself returns the string I am able to lay eggs.
Enter fullscreen mode Exit fullscreen mode

If two or more independently defined default methods conflict, or a default method conflicts with an abstract method, then the Java compiler produces a compiler error. You must explicitly override the supertype methods.

Consider the example about computer-controlled cars that can now fly. You have two interfaces (OperateCar and FlyCar) that provide default implementations for the same method, (startEngine):

public interface OperateCar {
    // ...
    default public int startEngine(EncryptedKey key) {
        // Implementation
    }
}
public interface FlyCar {
    // ...
    default public int startEngine(EncryptedKey key) {
        // Implementation
    }
}
Enter fullscreen mode Exit fullscreen mode

A class that implements both OperateCar and FlyCar must override the method startEngine. You could invoke any of the of the default implementations with the super keyword.

public class FlyingCar implements OperateCar, FlyCar {
    // ...
    public int startEngine(EncryptedKey key) {
        FlyCar.super.startEngine(key);
        OperateCar.super.startEngine(key);
    }
}
Enter fullscreen mode Exit fullscreen mode

The name preceding super (in this example, FlyCar or OperateCar) must refer to a direct superinterface that defines or inherits a default for the invoked method. This form of method invocation is not restricted to differentiating between multiple implemented interfaces that contain default methods with the same signature. You can use the super keyword to invoke a default method in both classes and interfaces.

Inherited instance methods from classes can override abstract interface methods. Consider the following interfaces and classes:

public interface Mammal {
    String identifyMyself();
}
public class Horse {
    public String identifyMyself() {
        return "I am a horse.";
    }
}
public class Mustang extends Horse implements Mammal {
    public static void main(String... args) {
        Mustang myApp = new Mustang();
        System.out.println(myApp.identifyMyself());
    }
}
Enter fullscreen mode Exit fullscreen mode

The method Mustang.identifyMyself returns the string I am a horse. The class Mustang inherits the method identifyMyself from the class Horse, which overrides the abstract method of the same name in the interface Mammal.

Note: Static methods in interfaces are never inherited.
Modifiers

The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

You will get a compile-time error if you attempt to change an instance method in the superclass to a static method in the subclass, and vice versa.
Summary

The following table summarizes what happens when you define a method with the same signature as a method in a superclass.
Defining a Method with the Same Signature as a Superclass's
Method

Superclass Instance Method

Subclass Instance Method:Overrides
Subclass Static Method:Generates a compile-time error

Superclass Static Method
Subclass Instance Method :Generates a compile-time error
Subclass Static Method :Hides

Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.

Top comments (0)