Sub topic 19
Abstract Class or Interface? Making the Choice
You now know both tools. An abstract class is a class that cannot be turned into an object and may hold fields, constructors, and finished methods. An interface is a named list of abstract methods that a class promises to provide. It can also carry default, static, and private methods. Both let you write code against a type without knowing the exact class behind it.
So when do you use which? This chapter gives you a simple way to decide. It also shows how the two often work together in one design.
The Core Difference in One Sentence
An abstract class says what something is. An interface says what something can do.
A Circle is a Shape. A Square can be drawn and can be resized. Shape is a family of related things. Drawable is an ability that unrelated things can share. A photo, a button, and a chart can all be drawn, and they have nothing else in common.
Side-by-Side Comparison
This table sums up the rules you met in earlier chapters.
| Feature | Abstract class | Interface |
|---|---|---|
| How many can a class use? | Only one (`extends`) | Many (`implements`) |
| Instance fields (state) | Yes, any kind | No, only constants |
| Constructors | Yes | No |
| Method bodies | Yes, any concrete method | Only `default`, `static`, `private` |
| Access levels for methods | Any: `public`, `protected`, `private` | Abstract and default methods are always `public` |
| Can be used with a lambda | No | Yes, if it is a functional interface |
| Good for | A family of closely related classes | An ability shared across unrelated classes |
The first row matters most. Java lets a class extend only one class. If you make something an abstract class, every subclass uses up its single extends slot on it. An interface costs nothing like that.
A Decision Guide
Ask these questions in order.
The diagram ends at "interface" as the default. Most experienced Java developers start with an interface. They add an abstract class only when the classes truly need to share state or setup code.
Signs You Need an Abstract Class
Choose an abstract class when one or more of these is true:
- The subclasses need the same fields, such as a
nameor anid. - The subclasses need the same setup steps in a constructor.
- You want to hide helper methods with
protectedorprivate, so outside code cannot call them. - You want to fix the order of steps with a
finalmethod, as in the template method pattern.
Signs You Need an Interface
Choose an interface when one or more of these is true:
- Classes from different families need the same ability.
- A class may need several abilities at once.
- You only describe behavior and do not store data.
- You want callers to supply behavior with a lambda, which is a short, unnamed function.
Using Both Together
Real designs often combine the two. The interface defines the public promise. An abstract class implements that interface and holds shared code for one family. Classes outside that family implement the interface directly.
Here is a payment example. Card payments share a card number and a counter, so they get an abstract class. A gift card works quite differently, so it implements the interface on its own.
interface PaymentMethod {
boolean pay(double amount);
String name();
}
abstract class CardPayment implements PaymentMethod {
private final String cardNumber;
private int attempts = 0;
protected CardPayment(String cardNumber) {
this.cardNumber = cardNumber;
}
@Override
public boolean pay(double amount) {
attempts++;
if (amount <= 0) {
return false;
}
return charge(amount);
}
protected abstract boolean charge(double amount);
protected String lastFour() {
return cardNumber.substring(cardNumber.length() - 4);
}
public int attempts() {
return attempts;
}
}
class VisaPayment extends CardPayment {
VisaPayment(String cardNumber) {
super(cardNumber);
}
@Override
protected boolean charge(double amount) {
System.out.println("Visa ending " + lastFour() + " charged " + amount);
return true;
}
@Override
public String name() {
return "Visa";
}
}
class GiftCard implements PaymentMethod {
private double balance;
GiftCard(double balance) {
this.balance = balance;
}
@Override
public boolean pay(double amount) {
if (amount > balance) {
return false;
}
balance -= amount;
return true;
}
@Override
public String name() {
return "Gift card";
}
}
public class Main {
public static void main(String[] args) {
PaymentMethod[] methods = {
new VisaPayment("4111111111111111"),
new GiftCard(20.0)
};
for (PaymentMethod m : methods) {
System.out.println(m.name() + " paid: " + m.pay(25.0));
}
}
}Running it prints:
Visa ending 1111 charged 25.0
Visa paid: true
Gift card paid: falseLook at what each part does:
PaymentMethodis the promise. The loop inmainonly knows this type.CardPaymentholds the state that all cards share: the card number and the attempt counter. It also runs the amount check once for every card type.GiftCarddoes not pretend to be a card. It skips the abstract class and implements the interface directly.
The Java library uses the same layout. List is an interface, AbstractList is an abstract class that implements it, and ArrayList extends AbstractList.
Common Mistakes
- Putting state in an interface. Fields in an interface are always
public static final, so they are constants. You cannot store per-object data there. - Making an interface too big. If a class has to write empty methods just to satisfy an interface, split it into smaller interfaces.
- Thinking default methods replace abstract classes. Default methods cannot read or change instance fields, because interfaces have none. If you need state, you still need a class.
- Forcing unrelated classes into one family. If
RobotextendsAnimalonly to get amove()method, the design is wrong. Use aMovableinterface instead.
Quick Checklist
- Write the interface first, describing what callers need.
- Ask whether several implementations repeat the same fields and setup.
- If they do, add an abstract class that implements the interface.
- Let callers depend on the interface type, not on the abstract class.
Exercise
You are designing a game. Players, enemies, and treasure chests can all be saved to a file, but they share no fields. Players and enemies both have health points and a name set in a constructor. Which types would you create, and would each be an abstract class or an interface?
Show answer
Create a Saveable interface, because saving is an ability shared by unrelated classes (players, enemies, chests). Create an abstract class such as Character that holds the name and health fields and a constructor that sets them. Player and Enemy extend Character, and Character (or each subclass) implements Saveable. TreasureChest implements Saveable directly, since it is not a character.
Exercise
A teammate writes an abstract class Printable with one abstract method print() and no fields, and makes Invoice extend it. Later Invoice must also extend a class called Document. What goes wrong, and how do you fix it?
Show answer
Java allows only one superclass, so Invoice cannot extend both Printable and Document. Since Printable has no fields or constructor, it should be an interface. Change it to "interface Printable { void print(); }" and write "class Invoice extends Document implements Printable". Remember to declare print() as public in Invoice.
Exercise
In the payment example, why is the amount check (amount <= 0) placed in CardPayment and not in VisaPayment?
Show answer
The check applies to every card type. Putting it in the abstract class's pay() method means it is written once and every subclass gets it automatically. Subclasses only fill in charge(), so a new card type cannot forget the check.