Method overriding in Java is a feature that allows a subclass to provide a specific implementation of a method that is already defined in its superclass.
This means that a subclass can redefine the behaviour of a method that it inherits from its superclass.
Polymorphism: Method overriding is a key mechanism for achieving polymorphism, allowing objects of different classes to be treated uniformly through a common interface.
Extensibility: Subclasses can provide their behaviour while maintaining a relationship with the superclass, enabling code extensibility and customization.
Encapsulation: Method overriding helps in encapsulate behaviour within classes, promoting a clear separation of concerns and modular design.
Key points about method overriding:
When overriding a method, the method in the subclass must have the same signature (name and parameters) as the method in the superclass.
The overriding method in the subclass cannot have a more restrictive access modifier than the overridden method in the superclass. However, it can have a less restrictive access modifier or the same access modifier.
The return type of the overriding method can be a subclass of the return type of the overridden method. In Java 5 and later, it can also be a covariant return type (i.e., a subtype of the return type of the overridden method).
class Animal { void makeSound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void makeSound() { System.out.println("Dog barks"); } void breedType() { System.out.println("german shepherd"); } }
the "Dog" class overrides the "makeSound" method inherited from the "Animal" class and has its own `breedType` method as well in `Dog` class
Then we can call "makeSound" on a "Dog" object, the overridden makeSound method in the "Dog" class will be executed instead of the "makeSound" method in the "Animal" class.
public class Main { public static void main(String[] args) { Animal animal = new Animal(); animal.makeSound(); // Output: "Animal makes a sound" Dog dog = new Dog(); dog.makeSound(); // Output: "Dog barks" } }
Method overriding allows for runtime polymorphism, where the actual method that gets executed is determined at runtime based on the object's type.
It enables subclasses to provide their specific implementation of methods inherited from their superclasses, enhancing code flexibility and extensibility in object-oriented programming.