Method Overriding in Java
Method overriding is a fundamental concept in Java's object-oriented programming (OOP) model. It allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This is a key feature of polymorphism, which enables objects of different classes to be treated as objects of a common superclass.
Here are the main rules for method overriding in Java:
1. Method Signature
The method signature (method name and parameter list) in the subclass must be exactly the same as the method signature in the superclass. The return type and the exceptions thrown can vary, as long as they follow the rules discussed below.
2. Access Modifier
The access modifier of the overriding method in the subclass must be the same or more accessible than the access modifier of the overridden method in the superclass. For example, if the method in the superclass is protected, the overriding method in the subclass can be protected or public, but not private.
3. Return Type
The return type of the overriding method must be the same or a subtype of the return type of the overridden method. This is known as covariant return type. For example, if the superclass method returns Object
, the overriding method can return String
.
4. Exceptions
The overriding method can throw fewer checked exceptions than the overridden method, or it can throw any unchecked exceptions, regardless of what the superclass method declares. However, the overriding method cannot throw new or broader checked exceptions than the overridden method.
Here's a simple example to illustrate method overriding in Java:
// Superclass
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
// Subclass
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.makeSound(); // Output: The animal makes a sound
Dog dog = new Dog();
dog.makeSound(); // Output: The dog barks
Animal animalRef = new Dog();
animalRef.makeSound(); // Output: The dog barks
}
}
In this example, the Dog
class overrides the makeSound()
method of the Animal
class. The overriding method in the Dog
class has the same method signature, but it provides a more specific implementation.
The last part of the example demonstrates polymorphism, where an Animal
reference can point to a Dog
object, and the overridden method is called based on the actual object type.
To help visualize the concept of method overriding, here's a Mermaid diagram:
This diagram shows the inheritance relationship between the Animal
and Dog
classes, and the overriding of the makeSound()
method in the Dog
class.
In summary, method overriding in Java allows subclasses to provide their own implementation of a method defined in the superclass, as long as they follow the rules regarding method signature, access modifier, return type, and exceptions.