OSJava.010: Java Interfaces, Abstract Classes and Default Methods

Original anime illustration of a developer studying modular Java software architecture, with BitcoinVersus.tech branding

Java interfaces define capabilities that different classes can implement; abstract classes provide shared foundations for related objects. Building on OSJava.009: inheritance and runtime polymorphism, the lesson uses a simulated equipment inventory to demonstrate both mechanisms.

Prerequisites and learning objectives

Use JDK 21 and a disposable local directory. Review classes and encapsulation and method signatures. By completion, learners should be able to declare and implement an interface; explain the state and constructor roles of an abstract class; dispatch operations through an interface reference; resolve conflicting default methods; and select a contract or abstract base appropriate to a design.

1. Interfaces as contracts

An interface introduces a reference type without per-object instance fields. Its abstract instance methods specify behavior that a concrete implementation must supply. In the sample, Reportable requires report(), which returns a String. A default method label() provides an inherited implementation that can call report(). Interface abstract methods are implicitly public; implementing methods must therefore be public. Classes may implement multiple interfaces, and interface constants are implicitly public, static and final. A default method is an instance method, not a static helper.

2. Abstract classes and shared state

An abstract class cannot be instantiated directly. It may hold instance fields, constructors, concrete methods and abstract methods. Device stores an identifier and provides a protected accessor; Switch invokes its constructor with super(id). Device does not implement report(), so it remains abstract. Switch is concrete because it supplies the missing implementation. Probe has no need for Device’s identifier and implements the same interface independently. Java classes can extend only one direct superclass. An interface is preferable when unrelated types need a common capability; an abstract class is useful when related types need shared state or implementation. Composition can supply reusable behavior without an inheritance relationship.

3. Local lab: reporting through a common interface

Save the following source as InterfaceLab.java. All readings are fabricated local strings, not hardware measurements.

interface Reportable {
    String report();
    default String label() { return "SIM: " + report(); }
}
abstract class Device implements Reportable {
    private final String id;
    Device(String id) { this.id = id; }
    protected String id() { return id; }
}
class Switch extends Device {
    Switch(String id) { super(id); }
    @Override public String report() { return id() + " link up"; }
}
class Probe implements Reportable {
    @Override public String report() { return "temperature 24 C"; }
}
public class InterfaceLab {
    public static void main(String[] args) {
        Reportable[] items = {new Switch("sw-01"), new Probe()};
        for (Reportable item : items) System.out.println(item.label());
    }
}

javac --release 21 InterfaceLab.java
java InterfaceLab

The lab was compiled and executed with javac 21.0.12.1. Output:

SIM: sw-01 link up
SIM: temperature 24 C

The array has interface reference type Reportable. Both Switch and Probe satisfy the contract, so label() can be invoked without knowing the concrete type. The default label() calls report(), and the runtime selects the implementation corresponding to the actual receiver. Review OSJava.006 arrays for the iteration mechanism.

4. Resolving conflicting default methods

If independent interfaces A and B both supply a default name() method with the same signature, a class implementing both must resolve the conflict explicitly, unless an applicable inherited method already resolves it. The class may define its own implementation or select a direct superinterface’s default via A.super.name(). A concrete superclass method generally takes precedence over interface defaults. The following independent example demonstrates an explicit choice.

interface A { default String name() { return "A"; } }
interface B { default String name() { return "B"; } }
class Combined implements A, B {
    @Override public String name() { return A.super.name(); }
}
public class ConflictLab {
    public static void main(String[] args) {
        System.out.println(new Combined().name());
    }
}

Save the second example as ConflictLab.java. Run javac –release 21 ConflictLab.java followed by java ConflictLab. The verified output is A. Changing the selected default to B.super.name() produces B.

5. Safe workflow and exercises

Keep the lab local. No production credentials, device connections or privileged commands are required. Real telemetry adapters require authorized access, validation, timeouts and change control. Exercise A: add a class Fan implementing Reportable that reports a simulated speed of 1200 RPM, then append a Fan to the array. Exercise B: remove public from Probe.report() and compile; restore it afterward. Exercise C: attempt new Device(“d-01”) and explain the failure. Exercise D: change Combined to return B.super.name(); explain the difference. Exercise E: choose a design for unrelated printers and routers that both export status, versus a family of switches sharing a serial number.

Knowledge check and answer key

1. Can an interface contain per-object fields? No. 2. Can an abstract class have a constructor? Yes; subclasses invoke it. 3. What chooses report() at runtime? The receiver’s actual class. 4. Why must conflicting unrelated defaults be resolved? Neither inherited implementation is inherently preferred. 5. When is composition useful? When reuse does not represent an is-a relationship.

Exercise answers: A prints an additional SIM: fan speed 1200 RPM line if that string is returned by Fan.report(). B fails because the implementation reduces the required public access. C fails because Device is abstract. D returns B rather than A. E: define a common status interface for unrelated equipment; consider an abstract base class for switches sharing state and behavior.

Glossary and authoritative references

Contract: operations promised by a type. Abstract class: non-instantiable class that can hold shared state and behavior. Default method: inherited interface instance implementation. Dynamic dispatch: selecting an implementation according to the actual object. See Dev.java: defining interfaces, implementing interfaces, and Oracle: abstract classes. For the normative rules, consult the Java SE 21 Language Specification, Chapter 9: Interfaces and Chapter 8: Classes. The official documentation and executable examples provide instructional references without relying on a third-party video player.

We volunteer daily to ensure the credibility of the information on our platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiative, please scan the QR code below.

BitcoinVersus.Tech voluntary donation QR code supporting independent technical research

Leave a Reply