DEV Community

PRIYA K
PRIYA K

Posted 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



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, and return type as the method in the parent class.
Instance methods can be overridden if they are inherited by the subclass

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

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.

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.

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.

Top comments (0)