Java: OOP – code examples
Class with inheritance
Use case: Bundle data and behavior, e.g. users, products, game characters.
public class Main {
static class Tier {
protected final String name;
Tier(String name) { this.name = name; }
String sprich() { return name + " makes a sound"; }
}
static class Hund extends Tier {
Hund(String name) { super(name); }
@Override String sprich() { return name + " says Woof!"; }
}
public static void main(String[] args) {
System.out.println(new Hund("Rex").sprich());
}
}Hund inherits from Tier (extends) and overrides sprich. super(name) calls the constructor of the base class.
Record with validation
OOP#record#dto#immutable
Use case: Immutable data objects (DTOs, return values) without getter boilerplate.
public class Main {
record Produkt(String name, double preis) {
Produkt {
if (preis < 0) throw new IllegalArgumentException("Price negative");
}
String label() { return name + " (" + preis + " EUR)"; }
}
public static void main(String[] args) {
var p = new Produkt("Coffee", 4.5);
System.out.println(p);
System.out.println(p.label());
System.out.println(p.equals(new Produkt("Coffee", 4.5)));
}
}The compact constructor checks values. toString, equals, hashCode and the accessor methods name() and preis() are generated by Java automatically. Output: Produkt[name=Coffee, preis=4.5], Coffee (4.5 EUR), true.
Enum with fields
OOP#enum#constants
Use case: Model fixed sets of choices (status, roles, weekdays) in a type-safe way.
public class Main {
enum Wochentag {
MONTAG(true), SAMSTAG(false);
private final boolean arbeitstag;
Wochentag(boolean a) { arbeitstag = a; }
boolean istArbeitstag() { return arbeitstag; }
}
public static void main(String[] args) {
for (Wochentag t : Wochentag.values()) {
System.out.println(t + " " + t.istArbeitstag());
}
System.out.println(Wochentag.valueOf("MONTAG").ordinal());
}
}Enums are full-fledged classes. values() returns all constants, valueOf looks up by name, ordinal() gives the position (0-based).