Abstract Classes

An abstract class is a partial blueprint: it can hold shared code, but leaves some methods for subclasses to fill in.

Java · beginner · 8 min · 21 steps · free

What you'll learn

AbstractDemo.java

abstract class Employee {
    String name;
    Employee(String name) { this.name = name; }

    abstract double pay();

    String payslip() {
        return name + ": " + pay();
    }
}

class Salaried extends Employee {
    Salaried(String name) { super(name); }
    double pay() { return 3000; }
}

class Hourly extends Employee {
    int hours;
    Hourly(String name, int hours) { super(name); this.hours = hours; }
    double pay() { return hours * 20; }
}

public class AbstractDemo {
    public static void main(String[] args) {
        Employee a = new Salaried("Asha");
        Employee b = new Hourly("Ben", 40);
        System.out.println(a.payslip());
        System.out.println(b.payslip());
    }
}

Step by step

  1. You cannot write new Employee(...), but you can make a Salaried, which is an Employee.
  2. Java runs the Employee constructor to set up the new object, with name = "Asha".
  3. Employee() has finished, so its variables are gone. name in the Salaried object changes from null to "Asha".
  4. Salaried() has finished, so its variables are gone.
  5. You cannot write new Employee(...), but you can make a Salaried, which is an Employee.
  6. Java runs the Hourly constructor to set up the new object, with name = "Ben" and hours = 40.
  7. Java runs the Employee constructor to set up the new object, with name = "Ben".
  8. Employee() has finished, so its variables are gone. name in the Hourly object changes from null to "Ben".
  9. Hourly() has finished, so its variables are gone.
  10. b is created on the stack and points to a new Hourly on the heap: {hours: 40, name: "Ben"}.
  11. Java calls payslip(). It gets its own variables on the stack.
  12. payslip() is shared code in Employee. It calls pay(), which each subclass defines.
  13. Salaried's pay: 3000.
  14. payslip() has finished, so its variables are gone.
  15. It prints Asha: 3000.0.
  16. Java calls payslip(). It gets its own variables on the stack.
  17. Same shared payslip(), now for Ben.
  18. pay() has finished, so its variables are gone.
  19. payslip() has finished, so its variables are gone.
  20. It prints Ben: 800.0.
  21. payslip() was written once; each subclass supplied its own pay().

Common mistakes

Best practices

Key takeaways

Check yourself

Can an abstract class have normal methods?

Answer: Yes. payslip() is a normal method.

A subclass does not implement pay(). Then?

Answer: It must be abstract too, or it will not compile. Concrete classes must implement every abstract method.

·

More in Object-Oriented Programming