Sub topic 11
Abstract Classes: Methods Every Subclass Must Provide
In earlier chapters, the Animal class had a sound() method that returned "...". That was a placeholder. A plain animal doesn't make any real sound, so the method only existed so that Dog and Cat could override it. Placeholders like this cause problems. Someone can forget to override the method, and the program will still run, quietly printing "...".
Java has a better tool for this: the abstract class. This chapter shows what abstract classes are, why they help, and the rules the compiler enforces for them.
What "Abstract" Means
An abstract class is a class marked with the abstract keyword. You cannot create objects of it directly. It exists only to be a superclass for other classes.
An abstract method is a method marked with abstract that has no body. It has a name, parameters, and a return type, then a semicolon where the curly braces would normally go. It says "every subclass must provide this method" without saying how.
A concrete class is an ordinary class that is not abstract. You can create objects of it with new.
Here is the basic shape:
abstract class Employee {
abstract double monthlyPay();
}The monthlyPay() method has no body. The class gives the method a name and leaves the work to each kind of employee.
Why Use an Abstract Class?
Think of a company payroll. Every employee gets a payslip. A salaried worker earns a fixed amount per year. An hourly worker earns a rate times the hours worked. The payslip looks the same for both, but the pay is calculated differently.
An abstract class lets you:
- Write the shared parts once, such as the employee's name and the payslip format.
- Require each subclass to supply the part that differs, which here is the pay calculation.
- Stop anyone from creating a vague "employee" that has no pay rule at all.
The compiler enforces the second and third points for you. You don't have to remember them.
A Worked Example: Payroll
This program defines an abstract Employee class and two concrete subclasses. Save it as Main.java, compile it with javac Main.java, and run it with java Main.
abstract class Employee {
private final String name;
Employee(String name) {
this.name = name;
}
abstract double monthlyPay();
String payslip() {
return name + ": " + monthlyPay();
}
}
class Salaried extends Employee {
private final double annual;
Salaried(String name, double annual) {
super(name);
this.annual = annual;
}
@Override
double monthlyPay() {
return annual / 12;
}
}
class Hourly extends Employee {
private final double rate;
private final int hours;
Hourly(String name, double rate, int hours) {
super(name);
this.rate = rate;
this.hours = hours;
}
@Override
double monthlyPay() {
return rate * hours;
}
}
public class Main {
public static void main(String[] args) {
Employee[] staff = {
new Salaried("Ana", 60000),
new Hourly("Ben", 20.0, 160)
};
for (Employee e : staff) {
System.out.println(e.payslip());
}
}
}The output is:
Ana: 5000.0
Ben: 3200.0Here is what happens, step by step:
Employeestores the name and definespayslip(). That method is concrete because it has a body.payslip()callsmonthlyPay(), even thoughEmployeenever says how pay is calculated.SalariedandHourlyeach overridemonthlyPay()with their own formula.- In the loop, each element's declared type is
Employee. Whenpayslip()callsmonthlyPay(), dynamic dispatch runs the version from the object's runtime class. Ana's object isSalaried, so its formula runs. Ben's object isHourly, so his formula runs.
This pattern has a name. When a superclass method lays out the steps and calls an abstract method for one of them, it is called the template method pattern. Here payslip() is the template, and monthlyPay() is the step each subclass fills in.
What an Abstract Class Can Contain
Beginners sometimes think an abstract class may only hold abstract methods. That is not true. An abstract class is a normal class with two extra features: it can declare abstract methods, and it cannot be created directly. It may contain:
| Member | Allowed in an abstract class? | Example from `Employee` |
|---|---|---|
| Fields | Yes | `private final String name` |
| Constructors | Yes | `Employee(String name)` |
| Concrete methods | Yes | `payslip()` |
| Abstract methods | Yes | `monthlyPay()` |
| Static methods | Yes | none here |
The constructor is worth a second look. You can never write new Employee("Ana"), so who calls it? The subclasses do. Salaried calls super(name) as the first line of its constructor. That runs the Employee constructor, which sets the name field for the new Salaried object.
The Rules the Compiler Enforces
Each rule below shows the mistake and the compiler error you will see. The exact wording can vary a little between Java versions.
Rule 1: You cannot create an abstract class with new
Employee e = new Employee("Zoe");
error: Employee is abstract; cannot be instantiatedA variable declared as Employee is fine. Only the object has to be a concrete subclass.
Rule 2: A concrete subclass must implement every abstract method
If Hourly left out monthlyPay(), you would see:
error: Hourly is not abstract and does not override abstract method monthlyPay() in EmployeeThis is the main benefit of the feature. The forgotten override that a placeholder method would hide becomes a compile error.
Rule 3: An abstract method has no body
abstract double monthlyPay() { return 0; }
error: abstract methods cannot have a bodyRule 4: A class with an abstract method must itself be abstract
If you declare an abstract method but leave abstract off the class, the compiler says the class "is not abstract and does not override abstract method". A class cannot be complete if one of its methods is missing.
Rule 5: Some modifiers clash with abstract
An abstract method exists to be overridden. Any modifier that blocks overriding conflicts with it:
| Combination | Why it fails |
|---|---|
| `abstract` + `private` | Subclasses cannot see a private method, so they cannot override it. |
| `abstract` + `final` | `final` forbids overriding. |
| `abstract` + `static` | Static methods are hidden, not overridden, and have no object to dispatch on. |
| `abstract class` + `final class` | A final class cannot have subclasses, so no class could ever fill in the missing methods. |
Edge Case: Abstract Subclasses
A subclass does not have to implement the abstract methods if it is also declared abstract. It passes the duty further down the hierarchy.
abstract class Contractor extends Employee {
Contractor(String name) {
super(name);
}
String agency() {
return "External";
}
}
class DailyContractor extends Contractor {
private final double dayRate;
private final int days;
DailyContractor(String name, double dayRate, int days) {
super(name);
this.dayRate = dayRate;
this.days = days;
}
@Override
double monthlyPay() {
return dayRate * days;
}
}Contractor adds a concrete agency() method but does not define monthlyPay(). That is allowed because Contractor is abstract. DailyContractor is concrete, so it must supply monthlyPay(). Add these classes to Main.java and you can put new DailyContractor("Cy", 300.0, 10) in the staff array. Its payslip prints Cy: 3000.0.
When to Choose an Abstract Class
Use an abstract class when:
- The subclasses really are kinds of one thing, such as kinds of employee.
- They share state (fields) or code that you want to write once.
- You want a constructor that every subclass runs.
A Java class can extend only one superclass. If unrelated classes need to share a set of methods, an interface is often the better choice. The next chapter covers interfaces.
Exercises
Exercise
Add a class Commissioned that extends Employee. Its constructor takes a name and a double sales, and its monthly pay is 10% of sales. What does new Commissioned("Dee", 40000).payslip() return?
Show answer
The class stores sales in a private final field, calls super(name) in its constructor, and overrides monthlyPay() to return sales * 0.10. The call returns "Dee: 4000.0".
Exercise
A student writes class Intern extends Employee with only a constructor and no monthlyPay() method. The code does not compile. Give two different ways to make it compile.
Show answer
Either add an @Override double monthlyPay() method with a body to Intern, or declare Intern as abstract (abstract class Intern extends Employee). The second fix means you can no longer create Intern objects directly.
Exercise
Is the line Employee e = new Hourly("Ben", 20.0, 160); legal, given that Employee is abstract? Explain.
Show answer
Yes. The declared type of a variable may be an abstract class. Only the object created with new must be of a concrete class, and Hourly is concrete. Calling e.monthlyPay() runs Hourly's version through dynamic dispatch.
Exercise
Why does the compiler reject private abstract double monthlyPay();?
Show answer
An abstract method must be overridden by a subclass, but a private method is not visible to subclasses and so can never be overridden. The two modifiers contradict each other.