Working with Inheritance
Working with Inheritance
This domain tests extends, implements, constructor chaining, overriding, polymorphism, casting, abstract classes, and interfaces. The central skill is knowing whether the compiler uses the reference type or the object type.
Inheritance rules
- A class extends one class and implements multiple interfaces. Constructors are not inherited; the first statement of every constructor is
super(...)orthis(...), inserted assuper()when absent. - Overriding requires the same signature, a covariant (same or narrower) return type, no reduction in visibility, and no broader checked exceptions.
staticmethods are hidden, not overridden;private,final, and constructors cannot be overridden. - A parent reference can refer to a child object. Instance method calls use the object's actual type (virtual dispatch); field access and static method calls use the reference type.
- Downcasting is explicit and may throw
ClassCastException; guard it withinstanceof. - Abstract classes may have constructors and both abstract and concrete methods. Interfaces declare constants (
public static final) and abstract methods; Java 8 addsdefaultandstaticmethods.
Worked example
class A { int x = 1; int getX() { return x; } }
class B extends A { int x = 2; int getX() { return x; } }
A a = new B();
System.out.println(a.x + " " + a.getX());
Field access a.x uses the compile-time type A, so it reads 1. The method call a.getX() dispatches to B, so it returns 2. Output: 1 2.
Traps
- Calling an overridable method from a constructor can run child code before child fields are initialized.
- A subclass cannot assign weaker access to an override.
super.superis not legal; you cannot skip a level.- Interface
defaultmethod conflicts must be resolved explicitly withInterfaceName.super.method(). - Casting to an unrelated sibling type fails at runtime even when it compiles.