About Lesson
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The method in the subclass must have the same name, parameter list, and return type as the method in the superclass.
Requirements for Method Overriding
- Same Method Signature: The method must have the same name, parameter list, and return type as the method in the superclass.
- Inheritance: The subclass inherits the method from the superclass.
- Return Type Must be Covariant: In method overriding, the return type of the method in the subclass must be the same as, or a subtype of, the return type of the method in the superclass. This concept is known as covariant return types.
- Runtime Polymorphism: Overriding is resolved at runtime.
- @Override Annotation: It is a good practice to use the
@Override
annotation to indicate that a method is intended to override a method in a superclass. - Access Modifier: The access level cannot be more restrictive than the overridden method’s access level. For example, if the superclass method is
public
, the subclass method cannot beprotected
orprivate
.
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
public void sound() {
System.out.println("Cat meows");
}
}
public class MethodOverridingExample {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.sound(); // Output: Dog barks
animal2.sound(); // Output: Cat meows
}
}