Inheritance allows one Java class to specialize another. Polymorphism lets an application invoke a shared operation while the runtime selects the implementation belonging to the actual object. The preceding OSJava.008 classes and objects lesson introduced constructors and encapsulation; the present lesson develops those ideas into a small inventory model.
Prerequisites and learning objectives
Prerequisites: JDK 21 or a compatible later JDK, familiarity with class definitions, constructors, arrays and Java methods. Use a local disposable working directory.
After completing the lesson, learners should be able to (1) define a subclass and call a superclass constructor, (2) override an instance method safely, (3) predict runtime dispatch through a superclass reference, (4) distinguish overriding from overloading and static hiding, and (5) recognize when composition is preferable to inheritance.
1. Superclasses, subclasses and constructor chains
A superclass defines a reusable type and its behavior. A subclass declares an is-a relationship using extends. Java classes have at most one direct superclass, although classes may implement multiple interfaces. A Switch is modeled as a Device, so a Device reference may refer to a Switch object. The Device class stores a private identifier; subclasses cannot directly access that private field. The inherited public id() method exposes the identifier without exposing mutable storage.
Constructors are not inherited. In the sample, super(id) calls the Device constructor, which initializes the identifier. Under Java 21, an explicit superclass constructor call appears first in the subclass constructor. If no explicit call is present, Java attempts an implicit no-argument superclass constructor call; compilation fails if that constructor is inaccessible or unavailable.
2. Overriding and access rules
An override supplies a subclass implementation of an inherited instance method with a compatible signature and return type. Java permits a covariant reference return type, but an overriding method cannot narrow access or broaden checked exceptions beyond the permitted inherited contract. The @Override annotation asks the compiler to check that an override actually exists. A misspelling or accidental parameter change can otherwise create a different method. Final methods cannot be overridden, and private methods are not inherited.
3. Dynamic dispatch and a local lab
Save the following example as DispatchLab.java in a new local directory. The array holds Device references, but its elements refer to two different concrete object types.
class Device {
private final String id;
Device(String id) { this.id = id; }
public String status() { return id + ": unknown"; }
public String id() { return id; }
}
class Switch extends Device {
Switch(String id) { super(id); }
@Override public String status() { return id() + ": link up"; }
}
class Server extends Device {
Server(String id) { super(id); }
@Override public String status() { return id() + ": ready"; }
}
public class DispatchLab {
public static void main(String[] args) {
Device[] inventory = {new Switch("sw-01"), new Server("srv-01")};
for (Device d : inventory) System.out.println(d.status());
}
}
Compile: javac DispatchLab.java. Run: java DispatchLab. Expected output: sw-01: link up followed by srv-01: ready. The example was compiled and executed with javac 21.0.12.1, producing both lines.
The compiler checks whether Device declares a callable status() operation. During execution, the JVM selects the overriding implementation according to the actual object. Consequently, the same source-level call produces different output for a Switch and a Server. A Device reference cannot directly call a method declared only on Switch without a suitable cast or pattern match. An invalid cast may fail at runtime with ClassCastException.
4. Overloading, hiding and composition
Overloading means defining methods with different parameter lists. Selection uses compile-time argument types and applicable signatures. Overriding concerns instance behavior selected at runtime. A static method is associated with its declaring class; a same-signature static method in a subclass hides rather than overrides the inherited static method. Fields are also not dynamically dispatched. Prefer qualifying static calls with the declaring class name.
Inheritance should model a stable is-a relationship and preserve the superclass contract. Composition instead represents a has-a relationship: a Server may contain a NetworkAdapter reference. A server is not a network adapter. Composition can reduce coupling by allowing an adapter implementation to be replaced without changing the server’s inheritance hierarchy.
5. Safe workflow and exercises
Use a local JDK only. No production device connections, administrative privileges, real credentials or network changes are needed. The sample status strings are simulated data rather than live device telemetry. In production, an inventory implementation would need authorization, input validation, change control and tests before accessing real devices.
Exercise A: Add a Router subclass whose constructor calls super(id) and whose status() returns the identifier followed by “: routing”. Add a Router to the array and predict the three lines. Exercise B: remove the parameter from super(id) and recompile; explain the error. Restore the original line. Exercise C: add status(int detail) to Switch, leaving status() unchanged; explain why the original Device loop does not call the overload. Exercise D: sketch a Server with a NetworkAdapter field and identify the relationship.
Knowledge check and answer key
1. Does a subclass inherit superclass constructors? No; a subclass constructor invokes a superclass constructor. 2. What decides which overridden instance method executes? The runtime class of the receiver object. 3. Can a public overriding method become private? No. 4. Does a static method use ordinary instance-method dynamic dispatch? No. 5. Which relationship best represents a server containing a network adapter? Composition.
Exercise answers: A: sw-01: link up; srv-01: ready; then the router identifier followed by “: routing”. B: Device has no no-argument constructor. C: status(int) has a different parameter list; the loop invokes status() without an argument. D: Server has a NetworkAdapter; store the adapter as a field rather than extending its class.
Glossary and references
Superclass: parent class. Subclass: specialized class. Override: compatible replacement of inherited instance behavior. Dynamic dispatch: runtime method selection using the receiver’s actual class. Composition: building an object from collaborating components. Covariant return: a permitted narrower reference return type.
Authoritative references: Dev.java inheritance; Oracle overriding and hiding; Oracle polymorphism. Review OSJava.006 arrays for the inventory array.
Leave a Reply