Method overriding in Java2 min read

Introduction

Method overriding in Java can be defined as a condition in which a child class has the same method as declared in the parent class. It has the advantage of allowing a subclass to define behavior that is specific to its type, allowing it to implement a parent class method based on its requirements. In object-oriented terms, overriding means overriding the functionality of an existing method.

In a class hierarchy, methods of two classes main have the same name and type signature. If the signature of a method in a subclass and superclass is the same then the method in a subclass.

When such a method is called within a subclass compiler always refers to the version of that method defined by the subclass. If we need to access the superclass version of the subclass method then it is super.

Method overriding in Java

Example:

class Animal{
  public void move(){
	System.out.println(Animals can move);
  }
}

class Dog extends Animal{
  public void move(){
  	System.out.println(Dogs can walk and run);
  }
}

public class TestDog{
  public static void main(String[] args){
  	Animal a = new Animal(); // Animal reference and object
  	Animal b = new Dog(); // Animal reference but Dog object
  	a.move();// runs the method in Animal class
  	b.move();//Runs the method in Dog class
  }
}

This would produce the following result:

Animals can move
Dogs can walk and run

Rules for method overriding in Java

  • The argument list should match that of the overridden method exactly.
  • The return type must be the same as or a subtype of the return type stated in the superclass’s original overridden method.
  • The access level must be lower than the access level of the overridden methods. For instance, if the superclass method is marked public, the subclass overriding method cannot be either private or protected.
  • Instance methods can only be overridden if the subclass inherits them.
  • It is not possible to override a method that has been declared final.
  • A static method cannot be overridden, but it can be re-declared.
  • A method can’t be overridden if it can’t be inherited.
  • Any superclass function that is not declared private or final can be overridden by a subclass in the same package as the instance’s superclass.
  • Only non-final methods labeled public or protected can be overridden by a subclass from a different package.
  • Regardless of whether the overridden method throws exceptions or not, an overriding method can throw any unchecked exceptions. The overriding method, on the other hand, should not throw any checked exceptions that aren’t specified by the overridden method. In comparison to the overridden method, the overriding method can throw fewer or narrower exceptions.

Share:

Leave a Reply