Polymorphism allows one superclass reference to refer to objects of different subclasses, with each object responding differently to the same method call. Method overriding enables this by giving a subclass its own implementation of a method inherited from its superclass.
How the mechanism works
Consider this Java-style example:
class Animal {
public void speak() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
public void speak() {
System.out.println("Bark");
}
}
class Cat extends Animal {
@Override
public void speak() {
System.out.println("Meow");
}
}
A superclass reference can store either subclass object:
Animal first = new Dog();
Animal second = new Cat();
first.speak(); // Bark
second.speak(); // Meow
The variables have the declared type Animal, but their objects have the runtime types Dog and Cat. During execution, dynamic method dispatch selects the overridden method belonging to the actual object. Therefore, first.speak() calls Dog.speak(), not Animal.speak().
For overriding to occur, the subclass method must have the same method name and parameter list as the inherited method. The @Override annotation is not the mechanism itself, but it helps the compiler detect mistakes.
| Concept | Meaning |
|---|---|
| Inheritance | A subclass acquires accessible attributes and methods from a superclass. |
| Method overriding | A subclass replaces an inherited method implementation. |
| Polymorphism | The same method call produces behaviour determined by the object’s runtime type. |
| Method overloading | Multiple methods share a name but have different parameter lists. |