Java Class Design
Java Class Design tests your ability to build legal inheritance hierarchies, apply encapsulation, and predict polymorphic behavior. Questions often ask which override compiles, what a constructor call dispatches to, or how access modifiers constrain an override.
Core rules
- A subclass method may widen access but never narrow it; it may return a covariant subtype and throw fewer or narrower checked exceptions.
private,static, andfinalmethods are not overridden:privatemethods are new declarations,staticmethods are hidden, andfinalmethods cannot be replaced.- Constructors are not inherited and are not polymorphic.
super(...)orthis(...)must be the first statement; if neither is written, the compiler insertssuper(). - An abstract class may have zero abstract methods but cannot be instantiated. A concrete subclass must implement all inherited abstract methods.
- Interface methods are implicitly
public abstract(exceptdefault/staticin Java 8); implementing methods must bepublic. - Fields are hidden, not overridden; field access depends on the reference type, while instance method calls use the runtime type.
Worked example
class A { public Number get() throws IOException { return 1; } }
class B extends A { @Override public Integer get() { return 2; } }
This compiles: Integer is covariant with Number, access stays public, and B.get() throws no checked exception. Calling new B().get() through an A reference still invokes B.get().
Traps
- Reducing visibility in an override is a compile error.
- Adding a broader checked exception than the overridden method is illegal.
staticmethods called through an instance resolve by reference type, not runtime type.- A
finalclass cannot be extended; afinalmethod cannot be overridden. - Calling an overridable method from a constructor runs before subclass fields are initialized.