9.1 Class Inheritance, extends & Method Overriding Rules
Key Takeaways
A normal class has at most one direct superclass. If its declaration omits extends, its direct superclass is Object, except that Object itself has none.
A final class cannot be subclassed. A class with only private constructors can be subclassed only where its constructor is accessible, such as a nested class in the same top-level declaration.
Constructors and private members are not inherited. A directly declared package-access member is not inherited by a direct subclass in a different package.
An instance override uses a subsignature, preserves or widens access, satisfies return-type compatibility, and cannot introduce a broader or new checked exception.
A subclass method matching a superclass private method is an unrelated new method, while a matching static method hides rather than overrides the superclass method
Class Inheritance, extends & Method Overriding Rules
Independent prep covering the class-inheritance and overriding objectives of Official Domain 7 (Working with Inheritance). Java uses inheritance to let a specialized subclass (child) reuse and customize state and behavior defined in a general superclass (parent). Exam questions frequently present short multi-class snippets and ask whether the code compiles, what it prints, or why a method declaration is rejected by javac.
Single Class Inheritance & the Object Root
A Java class can directly extend at most one class using the extends keyword. Attempting multiple class inheritance fails at compile time:
class Engine { }
class Chassis { }
// class Car extends Engine, Chassis { } // DOES NOT COMPILE: multiple classes after extends
A normal class with no explicit extends has Object as its direct superclass, except for Object itself. Enum declarations have a separate rule: their direct superclass is Enum<E> for the enum type E. In either hierarchy, methods such as toString(), equals(Object), hashCode(), and getClass() originate in Object.
public class Account { // Implicitly extends java.lang.Object
public String toString() {
return "Account";
}
}
Inheritance hierarchies must also remain acyclic. Writing class A extends B {} alongside class B extends A {} produces a compile-time cyclic inheritance error.
Preventing Subclassing: final Classes and private Constructors
Java offers two primary ways to prevent a class from being extended:
- Declare the class
final: Standard library classes such asjava.lang.String,java.lang.Integer, andjava.time.LocalDatearefinal. Any attempt to writeclass MyString extends String {}fails compilation. - Make all constructors
private: Every subclass constructor must call a superclass constructor (implicitly or viasuper(...)). If a class declares onlyprivateconstructors, external classes cannot callsuper(...)and therefore cannot subclass it. Note one subtle Java SE 8 detail: a nested class in the same enclosing top-level declaration can access the private constructor. For example, a static member classChildinside a non-finalBasecan extendBaseand call its private no-argument constructor.
Important
Marking a class final prevents all inheritance everywhere, including nested classes. A shared source file by itself does not grant private access. Making all constructors private blocks external subclassing while still allowing nested subclasses within the enclosing class body.
Inherited vs. Non-Inherited Members
Not every member written in a superclass becomes part of a subclass's inherited API. The table covers directly declared members of the immediate superclass, assuming the subclass does not hide or override the member and the declaring class is accessible:
| Superclass Member | Same-Package Subclass | Different-Package Subclass | Notes |
|---|---|---|---|
public field or method | Inherited | Inherited | Public access still depends on access to the relevant type |
protected field or method | Inherited | Inherited | Across packages, accessing a protected instance member in the subclass body requires a qualifier of that subclass type or a subtype |
| Package-private (default) member | Inherited | Not inherited | Package boundary blocks inheritance and overriding |
private field or method | Not inherited | Not inherited | Private access within the same top-level declaration is separate from inheritance |
| Constructors | Not inherited | Not inherited | Invoked via super(...), never inherited as subclass constructors |
Watch the cross-package protected rule—it is a classic trap:
// File: alpha/Base.java
package alpha;
public class Base {
protected int code = 42;
}
// File: beta/Derived.java
package beta;
import alpha.Base;
public class Derived extends Base {
public void inspect(Base b, Derived d) {
System.out.println(this.code); // Compiles: inherited via Derived
System.out.println(d.code); // Compiles: reference type is Derived
// System.out.println(b.code); // DOES NOT COMPILE: b has type Base in another package
}
}
Because Base is in package alpha and Derived is in package beta, Derived cannot read b.code through a Base reference, even though this.code and d.code compile cleanly.
The 5 Strict Method Overriding Rules
An instance method can override an accessible superclass instance method of which it has a subsignature. For ordinary non-generic methods, check the matching name and parameter types. The full Java SE 8 rule also allows certain erased signatures. To check an ordinary override, apply these rules:
| Rule | Requirement | Common Exam Trap |
|---|---|---|
| 1. Signature | A subsignature. For ordinary non-generic methods, same name and parameter types in the same order | Changing parameter types or count creates an overload, not an override |
| 2. Access Modifier | Same visibility or more accessible (private < default < protected < public) | Narrowing public to protected or protected to package-private fails compilation |
| 3. Return Type | Same type, or a covariant subtype for reference types (void must match void) | Primitive widening (int to long) or boxing (int to Integer) is not covariant and fails compilation |
| 4. Checked Exceptions | Same checked exceptions, narrower checked subtypes, or fewer/none | Adding a new or broader checked exception fails compilation; unchecked types, including the RuntimeException and Error branches, are exempt from this checked-exception restriction |
| 5. Overridable Target | Superclass method must be an accessible, non-final, non-static instance method | Cannot override final methods; matching private or static methods does not override |
Tracing Covariant Returns and Exception Narrowing
Consider a valid override vs. invalid overrides in Vehicle and ElectricCar:
import java.io.FileNotFoundException;
import java.io.IOException;
class Vehicle {
protected Number range() throws IOException {
return 300;
}
protected int wheels() {
return 4;
}
}
public class ElectricCar extends Vehicle {
@Override
public Integer range() throws FileNotFoundException { // VALID: public > protected, Integer < Number, FileNotFoundException < IOException
return 350;
}
// @Override
// public long wheels() { return 4L; } // DOES NOT COMPILE: long is not covariant with int
// @Override
// protected Number range() throws Exception { return 350; } // DOES NOT COMPILE: Exception is broader than IOException
}
In ElectricCar.range(), every rule is satisfied: public is broader than protected, Integer is a subtype of Number (covariant return), and FileNotFoundException is a subclass of IOException. Notice also that ElectricCar.range() could omit throws completely or add throws IllegalStateException (an unchecked RuntimeException) and still compile cleanly.
Package-Private Methods Across Packages
If a superclass defines a package-private (default-access) method void log() {} in package p1, and a subclass in package p2 defines void log() {}, the subclass method is not an override because the package-private method was never inherited across the package boundary. The two methods are completely independent.
@Override Safety, private Methods & static Method Hiding
Catching Accidental Overloads with @Override
Adding @Override instructs the compiler to verify that the method overrides or implements a supertype method, or has a signature matching a public method of Object under the annotation rule. Without @Override, a subtle parameter mismatch compiles silently as an overload:
class Ticket {
private final int id;
Ticket(int id) { this.id = id; }
// Accidental overload: parameter is Ticket, not Object!
public boolean equals(Ticket other) {
return other != null && this.id == other.id;
}
}
If you place @Override above public boolean equals(Ticket other), compilation immediately fails because Object defines equals(Object), not equals(Ticket). Always check parameter lists carefully when tracing exam code that lacks @Override.
private Methods Are Never Overridden
Because private methods are not inherited, a subclass can declare a method with the same name and parameters—even with a completely different return type or throws clause—and it is treated as a brand-new unrelated method:
class Parent {
private String secret() {
return "Parent";
}
public String reveal() {
return secret(); // Always calls Parent.secret()!
}
}
class Child extends Parent {
public int secret() { // Compiles! Brand-new method, NOT an override
return 99;
}
}
The expression new Child().reveal() returns "Parent" because Parent.reveal() calls Parent's private secret() method directly, and putting @Override on Child.secret() triggers a compile-time error.
Overriding vs. static Method Hiding
A static method belongs to the class, not an instance, so it cannot be overridden. If a subclass declares a static method with the same signature as an inherited static method, it hides the superclass method:
| Comparison | Instance Method Overriding | static Method Hiding |
|---|---|---|
| Modifiers on both methods | Both must be non-static | Both must be static |
Mixing static and instance | Compile-time error | Compile-time error |
| Signature, access, return, checked exceptions | All 4 overriding rules apply | All 4 rules still apply |
| Dispatch mechanism | Runtime object type | Compile-time type or class qualifier |
class Printer {
public static void info() { System.out.println("Printer"); }
public void print() { System.out.println("Generic"); }
}
class LaserPrinter extends Printer {
public static void info() { System.out.println("Laser"); } // Valid hiding
// public void info() { } // DOES NOT COMPILE: instance method cannot override static method
// public static void print() {} // DOES NOT COMPILE: static method cannot hide instance method
}
Warning
A static declaration cannot hide an accessible instance method, and an instance declaration cannot override an accessible static method. A same-signature private method in the superclass does not create that conflict.
Assume the named exception classes are imported and the declarations have appropriate method bodies. Which header can override protected Number compute() throws IOException in a subclass in another package?
Number compute() throws IOException
protected Double compute() throws Exception
public Integer compute() throws FileNotFoundException
public static Integer compute()
Consider a class Parent with private void audit() {} and a subclass Child extends Parent with @Override public int audit() { return 1; }. What is the result when compiling?
Compilation fails because @Override is placed on a method that does not override any inherited method
Compilation succeeds because public is broader than private
Compilation fails only because the return type changed from void to int
Compilation succeeds because Child hides Parent's private method
Which statement accurately describes inheritance involving a direct superclass and a separate top-level subclass in Java SE 8?
Subclasses inherit constructors from their direct superclass unless marked private
A subclass in a different package inherits package-private methods from its superclass
A class with only private constructors can still be subclassed by an unrelated top-level class in the same package
A subclass in a different package inherits an otherwise unhidden protected instance field. Code in the subclass cannot read it through a superclass-typed qualifier.
Sections you finish are checked off in the contents.