Java Method Overriding

https‮‬://www.theitroad.com

Method overriding is a feature of object-oriented programming that allows a subclass to provide a specific implementation of a method that is already defined in its parent class. In Java, method overriding is achieved by defining a method in a subclass that has the same signature (name, return type, and parameters) as a method in its parent class.

Here is an example of method overriding in Java:

class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow");
    }
}

In this example, the Cat class extends the Animal class and overrides the makeSound() method. When the makeSound() method is called on a Cat object, the Cat class's implementation of the method is executed, which prints "Meow" to the console.

When a method is overridden in a subclass, the subclass's implementation of the method is used instead of the parent class's implementation when the method is called on an object of the subclass. This allows subclasses to provide their own implementation of a method that is specific to their own behavior.

It's important to note that method overriding only applies to non-static methods, and that the access modifier of the overriding method cannot be more restrictive than the access modifier of the overridden method. Additionally, the @Override annotation can be used to indicate that a method is intended to override a method in its parent class.