Abstract Classes

A blueprint that isn't finished

Sometimes a parent class is too general to make objects from. What would a plain “Shape” look like? Mark such a class abstract. You can't create it with new, only its children.

An abstract method has no body – just a promise: “every child must write this method”.

abstract class Shape {
    String name;

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

    abstract double area();

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

class Circle extends Shape {
    double r;
    Circle(double r) {
        super("Circle");
        this.r = r;
    }

    @Override
    double area() { return Math.PI * r * r; }
}

class Rectangle extends Shape {
    double w, h;
    Rectangle(double w, double h) {
        super("Rectangle");
        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.5), new Rectangle(2, 5)};
        for (Shape s : shapes) {
            s.describe();
        }
    }
}

Output

Circle with area 7.07
Rectangle with area 10.00

Think of it like this: A form with blanks: the form (abstract class) has the layout and some text already filled in, but each person (child class) must fill in the blanks (abstract methods).

You can't make an abstract object

abstract class Shape {
    abstract double area();
}

public class Main {
    public static void main(String[] args) {
        Shape s = new Shape();
    }
}

Output (the program does not compile)

Main.java:7: error: Shape is abstract; cannot be instantiated
        Shape s = new Shape();
                  ^
HOME LABS COMMUNITY DASHBOARD