Sub topic 5
Constructors, Fields, and Shared Code in Abstract Classes
In the earlier chapters you saw that an abstract class cannot be created with new. That might make you think an abstract class is only a list of empty promises. It is not. An abstract class can hold real data, run real setup code, and share working methods with every subclass. This chapter shows how each of those pieces works and where beginners usually go wrong.
What an Abstract Class Can Hold
A field is a variable that belongs to an object. A constructor is the special block of code that runs when an object is created and sets up its fields. A concrete method is a normal method with a body.
An abstract class can have all three, plus abstract methods.
| Member | Allowed in an abstract class? | What it is for |
|---|---|---|
| Fields | Yes | Data every subclass object needs |
| Constructors | Yes | Setting up those fields once, in one place |
| Concrete methods | Yes | Behavior shared by all subclasses |
| Abstract methods | Yes | Steps each subclass must supply |
If an abstract class cannot be created with new, its constructor still has a job. It runs every time a subclass object is created. The subclass constructor calls it with super(...).
A Worked Example: Bank Accounts
Every bank account has an owner and a balance. Every account allows deposits. Only the monthly fee is different from one kind of account to another. So the shared data and code go in the abstract class, and the fee becomes an abstract method.
abstract class BankAccount {
private final String owner;
private double balance;
protected BankAccount(String owner, double openingBalance) {
if (openingBalance < 0) {
throw new IllegalArgumentException("Opening balance cannot be negative");
}
this.owner = owner;
this.balance = openingBalance;
}
public String getOwner() {
return owner;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Deposit must be positive");
}
balance += amount;
}
public void applyMonthlyFee() {
balance -= monthlyFee();
}
protected abstract double monthlyFee();
}
class CheckingAccount extends BankAccount {
CheckingAccount(String owner, double openingBalance) {
super(owner, openingBalance);
}
@Override
protected double monthlyFee() {
return 5.0;
}
}
class SavingsAccount extends BankAccount {
private final double minimumBalance;
SavingsAccount(String owner, double openingBalance, double minimumBalance) {
super(owner, openingBalance);
this.minimumBalance = minimumBalance;
}
@Override
protected double monthlyFee() {
return getBalance() >= minimumBalance ? 0.0 : 2.0;
}
}
public class Main {
public static void main(String[] args) {
BankAccount checking = new CheckingAccount("Ana", 100.0);
checking.deposit(50.0);
checking.applyMonthlyFee();
System.out.println(checking.getOwner() + ": " + checking.getBalance()); // Ana: 145.0
BankAccount savings = new SavingsAccount("Ben", 300.0, 500.0);
savings.applyMonthlyFee();
System.out.println(savings.getOwner() + ": " + savings.getBalance()); // Ben: 298.0
}
}Save this as Main.java, then run javac Main.java and java Main. You should see Ana: 145.0 and Ben: 298.0.
Look at what each class does:
BankAccountchecks the opening balance in one place. Neither subclass has to repeat that check.depositandapplyMonthlyFeeare written once and work for every account.applyMonthlyFeecallsmonthlyFee(), and the subclass decides what that returns.SavingsAccountadds its own field,minimumBalance, on top of the shared ones.
Why the Constructor Is `protected`
The protected keyword means "visible to subclasses (and the same package)". Nobody outside the class family can call new BankAccount(...), because the class is abstract. So making the constructor public adds nothing. Writing protected tells the reader that only subclasses are meant to use this constructor.
Private Fields, Public Getters
The fields owner and balance are private. This means even the subclasses cannot touch them directly. SavingsAccount reads the balance through getBalance(), which is a getter: a small method that returns a field's value.
Why not just make the fields protected? With protected fields, any subclass could write balance = -1000; and skip the checks in deposit. Private fields let the abstract class guarantee its own rules. The final keyword on owner adds one more guarantee: once the constructor sets it, it never changes.
The Order of Construction
When you write new SavingsAccount("Ben", 300.0, 500.0), Java builds the object from the top of the family down. The parent part is set up first, then the child part.
The call to super(...) must be the first statement in the subclass constructor. (Very recent Java versions loosen this rule a little, but writing super(...) first is still the normal style.)
Common Mistake: Forgetting `super(...)`
If a subclass constructor does not call super(...), Java quietly inserts super() with no arguments. BankAccount has no constructor without arguments, so this fails. If you deleted the super(owner, openingBalance); line from CheckingAccount, the compiler would report an error saying that the BankAccount constructor cannot be applied to the given types.
The fix is always the same: call the parent constructor that exists, passing the values it needs.
Edge Case: Calling an Abstract Method from a Constructor
This one surprises even experienced programmers. If the abstract class's constructor calls an abstract method, the subclass's version runs before the subclass's fields are set.
abstract class Base {
Base() {
System.out.println("Base sees: " + label());
}
abstract String label();
}
class Child extends Base {
private String name = "Child";
Child() {
super();
System.out.println("Child sees: " + label());
}
@Override
String label() {
return name;
}
}
public class Main {
public static void main(String[] args) {
new Child();
}
}The output is:
Base sees: null
Child sees: ChildWhile Base() runs, the line name = "Child" has not happened yet. That line runs only after super() returns. So label() returns null, which is the default value for an object field.
Summary
- Abstract classes can have fields, constructors, and concrete methods.
- Their constructors run through
super(...)each time a subclass object is created. - Put shared checks and shared code in the abstract class so subclasses do not repeat them.
- Keep fields
privateand provide getters, so the abstract class can protect its rules. - Never call abstract methods from a constructor.
Exercise
Add a withdraw(double amount) method to BankAccount that throws an IllegalArgumentException if the amount is not positive or is more than the balance. Should it go in the abstract class or in each subclass, and why?
Show answer
It goes in BankAccount, as a concrete method: public void withdraw(double amount) { if (amount <= 0 || amount > balance) { throw new IllegalArgumentException("Invalid withdrawal"); } balance -= amount; }. Every account withdraws the same way, and only BankAccount can change the private balance field, so writing it once there avoids duplication and keeps the balance rules in one place.
Exercise
A student writes class BusinessAccount extends BankAccount { BusinessAccount() { } protected double monthlyFee() { return 10.0; } }. Why does this fail to compile, and how do you fix it?
Show answer
The empty constructor gets an automatic super() call, but BankAccount has no constructor without arguments. Fix it by calling the existing constructor, for example BusinessAccount(String owner, double openingBalance) { super(owner, openingBalance); }.
Exercise
In the Base/Child example, why does the first line print null even though name is set to "Child" where it is declared?
Show answer
Field initializers in Child run only after the Base constructor finishes. While Base() is running, label() already uses Child's version, but name still holds its default value, null.