← 講座に戻る: Java from scratch

Abstract classes and interfaces

動画は近日公開

Imagine a Shape class. What is the area of a generic shape? It does not exist: it only makes sense for a concrete circle or rectangle. There are concepts that serve to group and define a contract, but that should not be instantiated. Java offers two tools for this: abstract classes and interfaces. Both define what can be done without saying how, and force concrete classes to provide the implementation. Knowing when to use each is a design decision made daily.

Abstract classes

An abstract class cannot be instantiated with new. It can have fields, constructors and normal methods with code, and also abstract methods, which only declare the signature without a body. Any concrete subclass must implement all abstract methods or the compiler will give an error. It is ideal when several classes share state and common code (for example the name of a shape and a method that prints it) and only differ in one part. A class can only inherit from one abstract class, just like from any other class.

java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Shape s = new Shape("x");       // error: Shape is abstract
        List<Shape> shapes = List.of(new Circle(1.5), new Rectangle(4, 2.5));
        double total = 0;
        for (Shape s : shapes) {
            s.describe();
            total += s.area();
        }
        System.out.printf("Total area: %.2f%n", total);
    }
}

abstract class Shape {
    private final String name;

    Shape(String name) { this.name = name; }

    abstract double area();          // each shape computes its own area

    void describe() {                // shared code
        System.out.printf("%s with area %.2f%n", name, area());
    }
}

class Circle extends Shape {
    private final double radius;
    Circle(double radius) { super("Circle"); this.radius = radius; }
    @Override double area() { return Math.PI * radius * radius; }
}

class Rectangle extends Shape {
    private final double width, height;
    Rectangle(double width, double height) {
        super("Rectangle");
        this.width = width;
        this.height = height;
    }
    @Override double area() { return width * height; }
}

Interfaces

An interface is a pure contract: it declares methods that a class promises to offer, regardless of its place in the hierarchy. You use implements, and a class can implement several interfaces at once, which solves the limitation of single inheritance. The methods of an interface are public and abstract by default; since Java 8 they can also have default methods (with code) and static ones. Typical names: Comparable, Runnable, Drawable, Payable. Think of an interface as what an object can do, while the parent class is what it is. A Duck and a Plane can both be Flyable even though they have nothing else in common.

java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Flyable> flyers = List.of(new Duck(), new Plane("A320"));
        for (Flyable f : flyers) {
            f.fly();
            f.land();                       // default method
        }

        // Comparable lets Collections.sort order your own objects
        List<Student> students = new ArrayList<>();
        students.add(new Student("Marta", 8.5));
        students.add(new Student("Ana", 9.2));
        students.add(new Student("Luis", 7.0));
        Collections.sort(students);
        for (Student s : students) System.out.println(s);
    }
}

interface Flyable {
    void fly();                              // abstract by default

    default void land() {                    // default method with code
        System.out.println("Landing...");
    }
}

class Duck implements Flyable {
    @Override public void fly() { System.out.println("The duck flaps its wings"); }
}

class Plane implements Flyable {
    private final String model;
    Plane(String model) { this.model = model; }
    @Override public void fly() { System.out.println(model + " takes off"); }
    @Override public void land() { System.out.println(model + " touches the runway"); }
}

class Student implements Comparable<Student> {
    private final String name;
    private final double grade;
    Student(String name, double grade) { this.name = name; this.grade = grade; }

    @Override
    public int compareTo(Student other) {
        return Double.compare(other.grade, this.grade);   // highest first
    }

    @Override public String toString() { return name + " (" + grade + ")"; }
}
  • Abstract class: state and common code, a single parent, strong is-a relationship.
  • Interface: capability or contract, several at once, no instance state (only constants).
  • A concrete class must implement all the abstract methods it inherits; otherwise it must be declared abstract.
  • Program against the interface: List<String> x = new ArrayList<>() lets you change the implementation without touching the rest.
  • A functional interface (with a single abstract method) can be written as a lambda; you will see it in week 8.
  • Since Java 17 there are sealed interfaces: they restrict which types may implement them.

One last modern example, combining sealed, records and switch with patterns. Note: switch with patterns over types and record deconstruction require Java 21; in Java 17 they were still a preview and do not compile without special options, which is why we do not run this example in the course with version 17. If you have JDK 21, copy and try the following code.

java
// Requires Java 21
sealed interface Figure permits Square, Circ { }
record Square(double side) implements Figure { }
record Circ(double radius) implements Figure { }

public class Main {
    static double area(Figure f) {
        return switch (f) {                    // exhaustive: no default needed
            case Square s -> s.side() * s.side();
            case Circ(double r) -> Math.PI * r * r;   // record pattern
        };
    }

    public static void main(String[] args) {
        System.out.println(area(new Square(3)));   // 9.0
    }
}

理解度チェック

問題 1 / 1

Can you do new Shape() if Shape is abstract?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →