Unlock the Power of Method Overriding in Java

What is Method Overriding?

Method overriding is a mechanism in Java that enables a subclass to provide a specific implementation of a method that is already defined in its superclass. This means that when you create a subclass, you can override a method of the superclass to provide a customized behavior.

How Does Method Overriding Work?

Let’s consider an example to illustrate how method overriding works. Suppose we have a superclass called Animal with a method displayInfo(), and a subclass called Dog that overrides this method.

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

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

When we create an object of the Dog class and call the displayInfo() method, the overridden method in the Dog class is executed, not the one in the Animal class.

Java Method Overriding Rules

To ensure that method overriding works correctly, Java enforces certain rules:

  • The method name, return type, and parameter list must be identical in both the superclass and subclass.
  • You cannot override a method that is declared as final or static.
  • Abstract methods in the superclass must be overridden in the subclass.

The Power of the super Keyword

But what if you want to access the method of the superclass from the subclass? That’s where the super keyword comes in. By using super, you can call the method of the superclass from the subclass, even if it’s been overridden.

public class Dog extends Animal {
    @Override
    public void displayInfo() {
        super.displayInfo(); // Calls the displayInfo() method of the Animal class
        System.out.println("I'm a dog.");
    }
}

Access Specifiers in Method Overriding

Did you know that the same method in the superclass and subclass can have different access specifiers? However, there’s a catch – the access specifier in the subclass must provide larger access than the one in the superclass.

  • If a method is declared protected in the superclass, it can be declared public or protected in the subclass, but not private.

Overriding Abstract Methods

In Java, abstract classes are designed to be the superclass of other classes. If a class contains an abstract method, it must be overridden in the subclass.

public abstract class Animal {
    public abstract void displayInfo();
}

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

By mastering method overriding, you can create more robust, flexible, and maintainable code in Java.

Leave a Reply