Inheritance and interfaces
Two ways to share and organise behaviour between classes: inheritance ("a Car is a Vehicle") reuses code from a parent class, and interfaces ("a Car can be Comparable") define abilities that many unrelated classes can promise to provide. Together they enable polymorphism: writing code that works with many types at once.
Inheritance with extends
class Animal {
protected final String name;
Animal(String name) { this.name = name; }
String sound() { return "..."; }
String speak() { return name + " says " + sound(); }
}
class Dog extends Animal {
Dog(String name) { super(name); } // call the parent's constructor first
@Override
String sound() { return "Woof"; }
void fetch() { System.out.println(name + " fetches the ball"); }
}
class Cat extends Animal {
Cat(String name) { super(name); }
@Override
String sound() { return "Meow"; }
}
public class Main {
public static void main(String[] args) {
Dog rex = new Dog("Rex");
System.out.println(rex.speak());
rex.fetch();
System.out.println(new Cat("Tom").speak());
}
}Rex says Woof Rex fetches the ball Tom says Meow
extendsmakesDoga subclass ofAnimal: it inheritsnameandspeak().super(name)calls the parent's constructor.@Overridemarks a method that replaces the parent's version. The compiler checks that you really are overriding something, which catches typos.- A class can extend only one class.
Polymorphism
A variable of the parent type can hold any subclass. When you call a method, the actual object's version runs:
class Shape {
double area() { return 0; }
}
class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }
}
class Rectangle extends Shape {
private final double w, h;
Rectangle(double w, double h) { this.w = w; this.h = h; }
@Override double area() { return w * h; }
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(1), new Rectangle(3, 4), new Circle(2) };
double total = 0;
for (Shape s : shapes) {
System.out.printf("%s: %.2f%n", s.getClass().getSimpleName(), s.area());
total += s.area();
}
System.out.printf("Total area: %.2f%n", total);
}
}Circle: 3.14 Rectangle: 12.00 Circle: 12.57 Total area: 27.71
The loop doesn't know or care which shapes it has. Add a Triangle class later, and this code works without changes.
Abstract classes
Shape.area() returning 0 is a fake answer. An abstract class can't be instantiated, and can declare abstract methods that every subclass must implement:
abstract class Employee {
protected final String name;
Employee(String name) { this.name = name; }
abstract double monthlyPay(); // no body: subclasses must provide one
String payslip() { // shared, concrete behaviour
return String.format("%-8s %10.2f", name, monthlyPay());
}
}
class Salaried extends Employee {
private final double annualSalary;
Salaried(String name, double annualSalary) { super(name); this.annualSalary = annualSalary; }
@Override double monthlyPay() { return annualSalary / 12; }
}
class Contractor extends Employee {
private final double hourlyRate;
private final int hours;
Contractor(String name, double hourlyRate, int hours) { super(name); this.hourlyRate = hourlyRate; this.hours = hours; }
@Override double monthlyPay() { return hourlyRate * hours; }
}
public class Main {
public static void main(String[] args) {
Employee[] staff = { new Salaried("Asha", 1_200_000), new Contractor("Rahul", 900, 120) };
for (Employee e : staff) System.out.println(e.payslip());
}
}Asha 100000.00 Rahul 108000.00
Interfaces
An interface is a contract: a list of methods a class promises to provide. A class can implement many interfaces, even if the classes are unrelated:
interface Payable {
double amountDue();
}
interface Notifiable {
void notify(String message);
default void remind() { // default method: has a body
notify("Friendly reminder: payment due");
}
}
class Invoice implements Payable, Notifiable {
private final String client;
private final double total;
Invoice(String client, double total) { this.client = client; this.total = total; }
public double amountDue() { return total; }
public void notify(String message) { System.out.println("Email to " + client + ": " + message); }
}
class Subscription implements Payable {
public double amountDue() { return 499; }
}
public class Main {
static double totalDue(Payable[] items) {
double sum = 0;
for (Payable p : items) sum += p.amountDue();
return sum;
}
public static void main(String[] args) {
Invoice inv = new Invoice("Acme", 12_000);
System.out.println(totalDue(new Payable[] { inv, new Subscription() }));
inv.remind();
}
}12499.0 Email to Acme: Friendly reminder: payment due
totalDue works with anything Payable: invoices, subscriptions, or classes nobody has written yet. Programming to interfaces is the backbone of large Java systems and frameworks like Spring.
Interfaces you'll use constantly
Comparable lets objects be sorted in their "natural" order:
import java.util.Arrays;
class Player implements Comparable<Player> {
final String name;
final int score;
Player(String name, int score) { this.name = name; this.score = score; }
@Override
public int compareTo(Player other) {
return Integer.compare(other.score, this.score); // highest score first
}
@Override
public String toString() { return name + "=" + score; }
}
public class Main {
public static void main(String[] args) {
Player[] board = { new Player("Asha", 1200), new Player("Rahul", 950), new Player("Priya", 1500) };
Arrays.sort(board);
System.out.println(Arrays.toString(board));
}
}[Priya=1500, Asha=1200, Rahul=950]
Other everyday interfaces: Runnable (a task to run), Iterable (usable in for-each loops), AutoCloseable (usable in try-with-resources) and Comparator (an external sort order, in the lambdas lesson).
Abstract class or interface?
| Abstract class | Interface | |
|---|---|---|
| A class can have | One parent | Many interfaces |
| Fields | Any (state) | Only constants |
| Constructors | Yes | No |
| Use for | Closely related classes sharing state and code | A capability many unrelated classes can have |
Composition over inheritance
Inheritance is powerful but rigid: a deep tree of subclasses becomes hard to change. Often it's better for a class to contain another object (composition) than to be one:
class Engine {
private final int horsepower;
Engine(int horsepower) { this.horsepower = horsepower; }
String start() { return "Vroom (" + horsepower + " hp)"; }
}
class Car {
private final String model;
private final Engine engine; // a Car HAS an Engine
Car(String model, Engine engine) { this.model = model; this.engine = engine; }
String drive() { return model + ": " + engine.start(); }
}
public class Main {
public static void main(String[] args) {
System.out.println(new Car("Hatchback", new Engine(90)).drive());
System.out.println(new Car("Sports", new Engine(400)).drive());
}
}Hatchback: Vroom (90 hp) Sports: Vroom (400 hp)
Use inheritance for true "is-a" relationships; use composition and interfaces for everything else.
Practice
- Create an abstract
Vehicleclass with an abstractwheels()method, andBikeandTrucksubclasses. Print the wheel count of each. - Create an interface
Discountablewithdouble discountedPrice(double percent), and implement it in aProductclass. - Make a
Studentclass implementComparable<Student>to sort students by grade, then by name.
1.How many classes can a Java class extend?
2.What does @Override do?
3.Shape s = new Circle(2); s.area(); Which area() runs?