Java 7: Inheritance & Method Overriding
easy⏱ 5 mincoursejava
Dynamic dispatch (polymorphism)
Java uses virtual method tables (vtables) — each class has a table mapping method signatures to implementations. At obj.method(), the JVM reads obj's actual class vtable (not the declared reference type). That's why Parent p = new Child(); p.speak(); calls Child.speak(). This is the mechanism behind polymorphism.
class Animal { String speak() { return "..."; } }
class Dog extends Animal { @Override String speak() { return "woof"; } }
class Cat extends Animal { @Override String speak() { return "meow"; } }
Animal a = new Dog();
System.out.println(a.speak()); // "woof"
Overriding constraints
A child override: (1) must have the same parameter types (not a compatible type — that's overloading), (2) may narrow the return type (covariant return: Object parent → String child), (3) can't narrow the access modifier, (4) can remove checked exceptions but not add new ones, (5) static methods are hidden not overridden (resolved by reference type).
Static methods are hidden, not overridden
class A { static void x() {...} } and class B extends A { static void x() {...} } — calling ((A)b).x() runs A.x(), not B.x(). Static methods don't participate in dynamic dispatch. This is a common interview gotcha.
A ref = new B();
ref.x(); // A.x() — NOT B.x(). Static calls bind at compile time.
Build a shape hierarchy
Define Shape (abstract) with area(). Create Circle, Rectangle, Square overrides. Put them in an array typed as Shape[] and compute the total area — polymorphism means you call area() once and each subclass's version runs. Print the class name + area per shape to prove the dispatch.
Mark with @Override, use final to lock
Always @Override — catches typos and signals intent. To prevent further overriding, mark a method final — useful for template methods and security-sensitive code. To prevent subclassing entirely, mark the class final (or sealed in modern Java, see Lesson 10).
Quiz: Covariant return
Can a child's overriding method return a different type? Only a subtype (covariant return). Parent returns Object, child can return String. Parent returns Number, child can return Integer. A completely unrelated type would not satisfy the parent's contract.