Abstract Classes

Rules

  • Declared with abstract class. It cannot be instantiated with new.
  • Can have abstract methods (no body) and normal methods with a body.
  • Can have fields, constructors and static methods.
  • A concrete subclass must implement every abstract method, or be abstract itself.

Abstract Class Example

Example

public class Main {
    public static void main(String[] args) {
        Employee[] staff = { new FullTimeEmployee("Asha", 60000), new Contractor("Ravi", 140, 500) };
        for (Employee e : staff) {
            e.printPayslip();
        }
        // Employee e = new Employee("X");   // error: Employee is abstract; cannot be instantiated
    }
}

abstract class Employee {
    protected final String name;

    Employee(String name) {             // abstract classes can have constructors
        this.name = name;
    }

    abstract double monthlyPay();       // no body: subclasses decide

    void printPayslip() {               // concrete method shared by all
        System.out.printf("%-6s : Rs %.2f%n", name, monthlyPay());
    }
}

class FullTimeEmployee extends Employee {
    private final double salary;
    FullTimeEmployee(String name, double salary) { super(name); this.salary = salary; }
    @Override double monthlyPay() { return salary; }
}

class Contractor extends Employee {
    private final int hours;
    private final double rate;
    Contractor(String name, int hours, double rate) { super(name); this.hours = hours; this.rate = rate; }
    @Override double monthlyPay() { return hours * rate; }
}

Output

Asha   : Rs 60000.00
Ravi   : Rs 70000.00

Practice

Exercise: Create an abstract class Shape with an abstract method double area() and a concrete method describe() that prints the area. Implement Square and Triangle.

Show answer
abstract class Shape {
    abstract double area();

    void describe() {
        System.out.println(getClass().getSimpleName() + " area: " + area());
    }
}

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

class Triangle extends Shape {
    double base, height;
    Triangle(double base, double height) { this.base = base; this.height = height; }
    double area() { return 0.5 * base * height; }
}