JvJava
IntermediateLesson 8 of 16

Classes, Inheritance & Interfaces – Java

Object orientation: encapsulation, constructors, inheritance, abstract classes, interfaces.

A class bundles data (fields) and behavior (methods). You make fields private and allow access only through methods (encapsulation). The constructor has the name of the class and no return type.

class Konto {
    private final String inhaber;
    private double saldo;

    Konto(String inhaber, double startSaldo) {
        this.inhaber = inhaber;
        this.saldo = startSaldo;
    }

    void einzahlen(double betrag) {
        if (betrag <= 0) throw new IllegalArgumentException("Amount must be positive");
        saldo += betrag;
    }

    double getSaldo() { return saldo; }

    @Override
    public String toString() { return inhaber + ": " + saldo; }
}

var k = new Konto("Ada", 100);
k.einzahlen(50);
System.out.println(k);        // Ada: 150.0

With extends you inherit from a class (only one!), with implements you implement any number of interfaces. @Override lets the compiler check that you really are overriding.

abstract class Tier {
    protected final String name;
    Tier(String name) { this.name = name; }
    abstract String sprich();               // without a body: subclasses must provide it
    void vorstellen() { System.out.println(name + ": " + sprich()); }
}

class Hund extends Tier {
    Hund(String name) { super(name); }
    @Override String sprich() { return "Woof!"; }
}

class Katze extends Tier {
    Katze(String name) { super(name); }
    @Override String sprich() { return "Meow!"; }
}

for (Tier t : new Tier[]{new Hund("Rex"), new Katze("Tom")}) {
    t.vorstellen();           // Rex: Woof!  /  Tom: Meow!
}

An interface describes a capability. Since Java 8 it may contain default methods with a ready-made implementation.

interface Bezahlbar {
    double preis();
    default double mitVersand() { return preis() + 4.5; }
}

class Buch implements Bezahlbar {
    public double preis() { return 10.0; }
}

System.out.println(new Buch().mitVersand());   // 14.5
WarningIf you override equals, you must also override hashCode – equal objects must have the same hash value, otherwise HashMap and HashSet do not work correctly. With record, Java does this automatically.
TipPrefer composition over inheritance: "has a" instead of "is a". Inheritance couples classes tightly to each other.