Method Overriding is a concept in Java that allows a subclass to provide a specific implementation of a method that is already defined in its superclass. When a method in a subclass has the same name, return type, and parameters as a method in its superclass, the method in the subclass overrides the method in the superclass.
Method overriding is an important feature of object-oriented programming because it allows subclasses to customize or extend the behavior of the methods defined in their superclass. It enables a subclass to provide a specific implementation of a method that is more suitable for the subclass's specific needs.
Here is an example that demonstrates method overriding in Java:
class Animal { public void makeSound() { System.out.println("Animal is making a sound"); } } class Dog extends Animal { @Override public void makeSound() { System.out.println("Dog is barking"); } } public class Main { public static void main(String[] args) { Animal animal = new Animal(); Dog dog = new Dog(); animal.makeSound(); // Output: Animal is making a sound dog.makeSound(); // Output: Dog is barking } }
In the above example, the Animal class has a method called makeSound(). The Dog class extends the Animal class and overrides the makeSound() method with its implementation. When the makeSound() method is called on an instance of the Animal class, the output is "Animal is making a sound." However, when the makeSound() method is called on an instance of the Dog class, the output is "Dog is barking," which is the specific implementation provided by the Dog class.