SyntaxPilot
Courses/Java/Lesson 20

Java · Lesson 20 of 51 · 10 min

Abstract classes

queued

These are the notes for Java episode 20. Episode 19 ended with an itch: a Shape parent has to return something from area(), so it returns a fake 0, and a Triangle that forgets to override area() silently has an area of zero. Today you make Java itself refuse that code. You will see the fake-zero bug give a wrong answer with no error, fix it with an abstract method (a method with no body that every child must fill in) and an abstract class (a class that can't be created with new), read the real errors "is not abstract and does not override abstract method" and "is abstract; cannot be instantiated", see what an abstract class can still hold (fields, constructors, normal methods), and learn every rule with its exact compiler message. Every example was run with javac 21.

The problem: order tiles for a floor made of shapes

A tile contractor gets the lobby of a new hotel: a mosaic floor made of a circle (radius 10 m), a square (side 3 m) and a triangle (base 4 m, height 5 m). He must order tiles for the total area:

Shape Formula Area
Circle, r = 10 3.14 × r × r 314 sq m
Square, side = 3 side × side 9 sq m
Triangle, base 4, height 5 ½ × base × height 10 sq m
Total 333 sq m

The obvious attempt: a parent that returns a fake 0

Using last episode's polymorphism, a Shape parent has area(), and each child overrides it. But a "shape in general" has no area, so the parent returns 0. The Triangle author forgot to override area(), and someone also put a plain new Shape() on the floor:

class Shape {
    double area() {
        return 0;
    }
}

class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }
    @Override double area() {
        return 3.14 * r * r;
    }
}

class Square extends Shape {
    double side;
    Square(double side) { this.side = side; }
    @Override double area() {
        return side * side;
    }
}

class Triangle extends Shape {
    double base, height;
    Triangle(double b, double h) {
        base = b;
        height = h;
    }
}

public class Main {
    public static void main(String[] args) {
        Shape[] floor = { new Circle(10), new Square(3),
            new Triangle(4, 5), new Shape() };
        double total = 0;
        for (Shape s : floor) {
            System.out.println(s.area());
            total += s.area();
        }
        System.out.println("Order tiles for " + total + " sq m");
    }
}
314.0
9.0
0.0
0.0
Order tiles for 323.0 sq m

323 instead of 333: ten square metres of floor get no tiles. And there was no error and no warning.

Why it went wrong

  • The parent was forced to invent an answer (0) for a question it can't answer.
  • Overriding is optional, so Java can't tell that Triangle forgot.
  • Nothing stops anyone from creating a "shape in general", which isn't a real shape.

We need a way to say: every shape has an area, but the parent can't compute it; each child must fill it in, and if one doesn't, refuse to compile.

Real-life example: a menu category can't be ordered

At a restaurant In Java
"Main course" is a heading on the menu; you can't order "one main course" abstract class Shape: a category, can't be created
Rule: every dish must show its price (the rule doesn't say what the price is) abstract double area();: a must-fill with no body
Paneer tikka, Rs 220: a real dish with a real price class Circle fills in area()
The plate and service are the same for every dish a normal method like describe() shared by all children

Abstract methods and abstract classes

abstract double area();        // abstract method: no { } body, ends with ;
abstract class Shape { ... }   // abstract class: can't be created with new
  • Abstract method: a method declared with abstract and no body. It's a promise ("every shape has an area") with the work left to the children.
  • Abstract class: a class declared with abstract. It can't be instantiated (instantiate = create an object of it with new); it can only be extended. A class that has an abstract method must be abstract, because it is unfinished.
  • Concrete class: a normal, non-abstract class that can be created with new. To be concrete, a child must override every abstract method it inherits.

Java enforces it

abstract class Shape {
    abstract double area();
}

class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }
    @Override double area() {
        return 3.14 * r * r;
    }
}

class Triangle extends Shape {
    double base, height;
    Triangle(double b, double h) {
        base = b;
        height = h;
    }
}

public class Main {
    public static void main(String[] args) {
        Shape[] floor = { new Circle(10),
            new Triangle(4, 5), new Shape() };
        for (Shape s : floor) {
            System.out.println(s.area());
        }
    }
}
Main.java:13: error: Triangle is not abstract and does not override abstract method area() in Shape
class Triangle extends Shape {
^
Main.java:24: error: Shape is abstract; cannot be instantiated
            new Triangle(4, 5), new Shape() };
                                ^
2 errors

Both silent bugs are now compile errors: the program can't run until they're fixed.

What an abstract class can hold

Abstract doesn't mean empty. An abstract class can have:

Member Example Notes
Fields String name; data every child has
Constructors Shape(String name) runs when a child calls super(...); you still can't call new Shape(...)
Abstract methods abstract double area(); each concrete child must override
Normal (concrete) methods void describe() shared code; may call abstract methods
Static methods and constants static final double PI = 3.14; as in any class

The complete version

abstract class Shape {
    String name;
    Shape(String name) { this.name = name; }
    abstract double area();
    void describe() {
        System.out.println(name + ": " + area() + " sq m");
    }
}

class Circle extends Shape {
    double r;
    Circle(double r) { super("Circle"); this.r = r; }
    @Override double area() { return 3.14 * r * r; }
}

class Square extends Shape {
    double side;
    Square(double s) { super("Square"); side = s; }
    @Override double area() { return side * side; }
}

class Triangle extends Shape {
    double base, height;
    Triangle(double b, double h) {
        super("Triangle");
        base = b;
        height = h;
    }
    @Override double area() { return 0.5 * base * height; }
}

public class Main {
    public static void main(String[] args) {
        Shape[] floor = { new Circle(10), new Square(3),
            new Triangle(4, 5) };
        double total = 0;
        for (Shape s : floor) {
            s.describe();
            total += s.area();
        }
        System.out.println("Order tiles for " + total + " sq m");
    }
}
Circle: 314.0 sq m
Square: 9.0 sq m
Triangle: 10.0 sq m
Order tiles for 333.0 sq m

describe() is written once, in the parent, and calls area(); each time, the child's own area() runs. The parent writes the common steps and the child supplies the missing piece. (This shape of design has a name you'll meet in the design-patterns episode: the template method pattern.)

An abstract type is still a type

Shape s = new Circle(10);      // OK: a Circle IS a Shape (upcasting)
s.describe();                  // Circle: 314.0 sq m
Shape[] floor = new Shape[3];  // OK: three empty slots, no Shape objects created
Shape t = new Shape();         // error: Shape is abstract; cannot be instantiated

The rules

  1. An abstract method has no body and ends with ;.
  2. A class with an abstract method must be abstract.
  3. A child must override all inherited abstract methods, or be declared abstract itself (passing the job to its own children).
  4. An abstract class may have zero abstract methods (useful just to stop direct creation).
  5. abstract can't be combined with final, private or static: abstract means "a child must override", while final means "no one may override", private means "children can't see it", and static methods aren't overridden.

A middle class can stay abstract and fill in only some methods:

abstract class Shape { abstract double area(); abstract double perimeter(); }
abstract class Polygon extends Shape {
    double perimeter() { return 0; }
}
class Square extends Polygon {
    double s = 2;
    double area() { return s * s; }
    double perimeter() { return 4 * s; }
}
public class Main { public static void main(String[] a) { Shape x = new Square(); System.out.println(x.area() + " " + x.perimeter()); } }
4.0 8.0

What you just invented

Problem Fix
A parent with no honest answer returns a fake value abstract method: a must-fill with no body
A child forgets to override, silently Compile error: "is not abstract and does not override abstract method"
A "shape in general" gets created abstract class: "is abstract; cannot be instantiated"
Shared code for all children Normal methods in the abstract class, calling abstract ones

That's an abstract class: silent wrong answers became compile errors.

The next problem: a Duck is a Bird (abstract, with fly()), but it also swims, and we have an abstract Swimmer with swim(). class Duck extends Bird, Swimmer gives error: '{' expected: a Java class can extend only one class. Episode 21: interfaces.

Common mistakes (and the real error messages)

Mistake Real message Why Fix
new Shape() error: Shape is abstract; cannot be instantiated An abstract class is only a category Create a child: new Circle(10)
A child without area() error: Triangle is not abstract and does not override abstract method area() in Shape Every must-fill must be filled Override area(), or make the child abstract
abstract double area() { return 0; } error: abstract methods cannot have a body abstract = no body abstract double area();
double area(); in a class error: missing method body, or declare abstract A normal method needs a body Add abstract or write the body
class Shape { abstract double area(); } error: Shape is not abstract and does not override abstract method area() in Shape A class with an abstract method must be abstract abstract class Shape
final abstract double area(); error: illegal combination of modifiers: abstract and final must override vs may never override drop final
private abstract double area(); error: illegal combination of modifiers: abstract and private children can't see a private method make it package-private, protected or public
static abstract double area(); error: illegal combination of modifiers: abstract and static static methods aren't overridden drop static
class Duck extends Bird, Swimmer error: '{' expected one parent class only interfaces (episode 21)

Mini project: a payroll

An abstract Employee with a constructor, a field, an abstract monthlyPay() and a shared payslip():

abstract class Employee {
    String name;
    Employee(String name) { this.name = name; }
    abstract double monthlyPay();
    void payslip() {
        System.out.printf("%-8s Rs %.2f%n", name, monthlyPay());
    }
}
class FullTime extends Employee {
    double salary;
    FullTime(String n, double s) { super(n); salary = s; }
    double monthlyPay() { return salary / 12; }
}
class Intern extends Employee {
    double stipend;
    Intern(String n, double s) { super(n); stipend = s; }
    double monthlyPay() { return stipend; }
}
class Freelancer extends Employee {
    int hours; double rate;
    Freelancer(String n, int h, double r) { super(n); hours = h; rate = r; }
    double monthlyPay() { return hours * rate; }
}
public class Main {
    public static void main(String[] args) {
        Employee[] team = { new FullTime("Priya", 900000), new Intern("Rohan", 15000), new Freelancer("Kabir", 40, 750) };
        double total = 0;
        for (Employee e : team) { e.payslip(); total += e.monthlyPay(); }
        System.out.printf("Total    Rs %.2f%n", total);
    }
}
Priya    Rs 75000.00
Rohan    Rs 15000.00
Kabir    Rs 30000.00
Total    Rs 120000.00

Adding a Contractor means one new class, and the compiler makes sure it has monthlyPay().

Practice

  1. Add a Rectangle (length 6, width 2) to the floor. What is the new total?
  2. Mark Triangle as abstract in the complete version. What breaks, and where?
  3. Predict the output (a classic trap):
abstract class Base {
    Base() {
        System.out.println("Base sees: " + value());
    }
    abstract int value();
}

class Child extends Base {
    int x = 42;
    Child() {
        System.out.println("Child sees: " + value());
    }
    int value() { return x; }
}

public class Main {
    public static void main(String[] args) {
        new Child();
    }
}
  1. Can an abstract class have no abstract methods? Write one and use it.
Solutions

1.

class Rectangle extends Shape {
    double length, width;
    Rectangle(double l, double w) {
        super("Rectangle");
        length = l;
        width = w;
    }
    @Override double area() { return length * width; }
}
// floor = { new Circle(10), new Square(3), new Triangle(4, 5), new Rectangle(6, 2) }
Circle: 314.0 sq m
Square: 9.0 sq m
Triangle: 10.0 sq m
Rectangle: 12.0 sq m
Order tiles for 345.0 sq m

2. The class itself compiles, but creating one fails:

Main.java:35: error: Triangle is abstract; cannot be instantiated
            new Triangle(4, 5) };
            ^
1 error

3.

Base sees: 0
Child sees: 42

The parent constructor runs before the child's fields are initialised, but value() already runs the child's override, which reads x while it is still 0. Lesson: don't call overridable methods from a constructor.

4. Yes:

abstract class Report {
    void print() { System.out.println("Report"); }
}
class Sales extends Report { }
public class Main {
    public static void main(String[] args) {
        Report r = new Sales();
        r.print();
    }
}
Report

Quick quiz

abstract class Snack {
    Snack() { System.out.print("Snack "); }
    abstract String name();
    void serve() { System.out.print(name() + " "); }
}
class Samosa extends Snack {
    Samosa() { System.out.print("Samosa "); }
    String name() { return "hot-samosa"; }
}
// in main:
Snack s = new Samosa();
s.serve();

A) Compile error: Snack is abstract B) Samosa hot-samosa C) Snack Samosa hot-samosa D) Snack Samosa null

Answer

C. Snack s = new Samosa() creates a Samosa (allowed), and building it runs the abstract parent's constructor first (Snack), then the child's (Samosa). serve() is inherited and calls the child's name(): hot-samosa.

Interview questions

  1. What is an abstract class? A class declared abstract that can't be instantiated; it exists to be extended, and may contain abstract methods (no body) as well as fields, constructors and concrete methods.
  2. Can an abstract class have a constructor? Yes. It runs when a subclass object is created, through super(...).
  3. Can an abstract class have no abstract methods? Yes; it just can't be instantiated.
  4. Can you create a reference of an abstract type? Yes: Shape s = new Circle(10);.
  5. Why can't a method be both abstract and final / private / static? Abstract requires overriding; final forbids it, private hides it from subclasses, and static methods aren't overridden.
  6. What happens if a subclass doesn't implement all abstract methods? It must be declared abstract itself, or compilation fails with "is not abstract and does not override abstract method".
  7. What is abstraction? Showing what something does while hiding how: callers use area() without knowing each formula. Abstract classes (and interfaces, next episode) are Java's tools for it.
  8. Can you create an object of an abstract class with an anonymous class? Yes: new Shape() { double area() { return 7.5; } } creates an object of an unnamed concrete subclass (episode 23).

Glossary

Term Meaning Example
Abstract method A method with no body that subclasses must override abstract double area();
Abstract class A class that can't be instantiated; meant to be extended abstract class Shape
Concrete class A class with all methods implemented; can be created with new Circle
Instantiate Create an object of a class with new new Circle(10)
Abstraction Exposing what something does, hiding how callers use area()
Must-fill (our nickname) an abstract method every concrete child must fill in area()
super(...) Calls the parent's constructor from a child's constructor super("Circle")
Template method A parent method that fixes the steps and calls abstract methods for the varying part describe() calling area()
Modifier A keyword that changes a declaration's meaning abstract, final, static, private
Upcasting Storing a child object in a parent-type variable Shape s = new Circle(10);

Summary

  • A parent that returns a fake answer (return 0;) hides bugs that compile and run silently.
  • An abstract method has no body; every concrete child must override it.
  • An abstract class can't be created with new; it's a category that holds shared fields, constructors and methods.
  • A normal method in the parent can call an abstract one: the parent fixes the steps, the child fills the gap.
  • Abstract types still work as references and arrays.
  • abstract + final / private / static is illegal.
  • Next: a duck that must be a Bird and a Swimmer, but Java allows one parent class. Episode 21: interfaces.