Part 08 / Topic 8 of 12
Abstract classes
An abstract class is a class you can never new directly — it is marked abstract and can leave one or more methods with no body (also marked abstract), as a promise that every concrete subclass will supply one. It sits between "ordinary class" and "interface" (section 9): it can hold real fields and finished methods, same as any class, but it can also leave specific pieces undone on purpose.
Think of a loan-application form with a blank marked "attach proof of income here": the form itself is not a complete application, and nobody files the blank form — only a filled-in copy that supplies the missing piece.
Real-world example: BankAccount becomes abstract once "every account has some monthly fee rule, but the rule itself differs by account type" is the actual design.
abstract static class BankAccount {
protected final String accountNumber;
protected double balance;
BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
abstract double monthlyFee(); // no body: every concrete subclass must supply one
String statementLine() { // a normal method; it can call the abstract one
return accountNumber + ": balance ₹" + balance + ", fee ₹" + monthlyFee();
}
}
static class SavingsAccount extends BankAccount {
SavingsAccount(String accountNumber, double balance) { super(accountNumber, balance); }
@Override double monthlyFee() { return 0.0; }
}
static class CurrentAccount extends BankAccount {
CurrentAccount(String accountNumber, double balance) { super(accountNumber, balance); }
@Override double monthlyFee() { return 150.0; }
}
SBIN0001234: balance ₹50000.0, fee ₹0.0
HDFC0005678: balance ₹120000.0, fee ₹150.0
Trying to build the abstract class directly refuses to even compile:
$ javac AbstractProbe.java
AbstractProbe.java:6: error: BankAccount is abstract; cannot be instantiated
BankAccount acc = new BankAccount("X");
^
1 error
statementLine() is not abstract, and calls monthlyFee() on this without knowing which override will run — exactly the polymorphism from section 7, now happening inside a method the abstract class itself wrote. This is the real reason to reach for abstract instead of a plain superclass with a monthlyFee() that just return 0.0;: a plain default is easy to forget to override, silently giving a new account type the wrong fee; an abstract method makes the compiler refuse to build MoneyMarketAccount at all until someone writes its monthlyFee().
Full program: examples/AbstractClasses.java.
Done here? The practice set for Part 8 — including the solutions — is on the part page.