JAVA-102 · Lesson 6 of 12 · 21 min
Abstract classes and interfaces
▶ Video coming soon A video version of this lesson is on the way.
After lesson 5 the booking system had a Booking superclass and two subclasses, RepairBooking and RentalBooking. Hamza then noticed something odd: the program could still create a plain new Booking(...), which is neither a repair nor a rental and makes no sense at the counter. Ingrid also pointed out that bookings are not the only things with prices. Parts, rentals, repair jobs and gift cards all have a price and tax, but they are not related by is-a. The plan for Wednesday, February 24, 2027, after the college's reading week, covers Java's two tools for these problems: abstract classes and interfaces.
Abstract classes
A class declared abstract cannot be instantiated with new. It exists only to be extended. An abstract class can have fields, constructors and ordinary methods like any class, and it can also declare abstract methods: methods with no body, ending in a semicolon, that every concrete subclass must implement. A subclass that does not implement all of them must itself be abstract.
public class Main {
public static void main(String[] args) {
Booking[] today = {
new RepairBooking("Ana Ruiz", "brake bleed", 4500),
new RentalBooking("Theo Park", 3, 1500),
};
for (Booking b : today) {
System.out.println(b.describe() + " -> " + b.priceCents() + " cents");
}
}
}
abstract class Booking {
private final String customer;
Booking(String customer) {
this.customer = customer;
}
String getCustomer() { return customer; }
abstract long priceCents();
abstract String summary();
String describe() {
return customer + ": " + summary();
}
}
class RepairBooking extends Booking {
private final String job;
private final long quoteCents;
RepairBooking(String customer, String job, long quoteCents) {
super(customer);
this.job = job;
this.quoteCents = quoteCents;
}
@Override long priceCents() { return quoteCents; }
@Override String summary() { return "repair, " + job; }
}
class RentalBooking extends Booking {
private final int days;
private final long dailyCents;
RentalBooking(String customer, int days, long dailyCents) {
super(customer);
this.days = days;
this.dailyCents = dailyCents;
}
@Override long priceCents() { return days * dailyCents; }
@Override String summary() { return "rental, " + days + " days"; }
}Ana Ruiz: repair, brake bleed -> 4500 cents Theo Park: rental, 3 days -> 4500 cents
What this code does
Booking is abstract, so new Booking(...) no longer compiles, and it declares priceCents and summary without bodies. Each concrete subclass must implement both, in its own way. describe is an ordinary method in Booking that calls the abstract summary, so it works for every kind of booking.
public class Main {
public static void main(String[] args) {
Booking b = new Booking("Ana Ruiz");
}
}
abstract class Booking {
private final String customer;
Booking(String customer) { this.customer = customer; }
abstract long priceCents();
}What this code does
Booking is abstract, so creating one directly is not allowed. javac reports that Booking is abstract and cannot be instantiated. Only concrete subclasses such as RepairBooking can be created with new.
$ javac Main.java
Main.java:3: error: Booking is abstract; cannot be instantiated
Booking b = new Booking("Ana Ruiz");
^
1 errorAn abstract class can still have a constructor, as Booking does: it runs when a subclass constructor calls super(...). The abstract class gives every subclass its shared state and behavior while forcing each one to fill in the parts only it knows.
Interfaces
An interface describes what a type can do without saying how. It lists method signatures, and any class that declares implements with the interface's name promises to provide those methods. An interface has no instance fields and no constructors. Its methods are public and abstract unless you give them a body with default, static or private, which the next sections cover.
Unlike extends, a class can implement any number of interfaces. That is how unrelated classes can share a capability: a Part, a RentalBooking and a GiftCard are not related by is-a, but each can be Priced.
public class Main {
public static void main(String[] args) {
Priced[] cart = {
new Part("700x25c inner tube", 899),
new GiftCard(2500),
new Part("brake pads", 1650),
};
long total = 0;
for (Priced item : cart) {
System.out.println(item.label() + ": " + item.priceCents());
total += item.priceCents();
}
System.out.println("Total: " + total + " cents");
}
}
interface Priced {
long priceCents();
String label();
}
class Part implements Priced {
private final String name;
private final long cents;
Part(String name, long cents) {
this.name = name;
this.cents = cents;
}
@Override public long priceCents() { return cents; }
@Override public String label() { return name; }
}
class GiftCard implements Priced {
private final long valueCents;
GiftCard(long valueCents) {
this.valueCents = valueCents;
}
@Override public long priceCents() { return valueCents; }
@Override public String label() { return "gift card"; }
}700x25c inner tube: 899 gift card: 2500 brake pads: 1650 Total: 5049 cents
What this code does
Priced lists two methods, and Part and GiftCard each implement them in their own way. The cart is an array of Priced, so the loop can total any mix of items without knowing their classes. The implementing methods must be public, because interface methods are public.
An interface name can be used as a type for variables, parameters, arrays and return values. Code written against Priced works with every class that implements it, including classes written next year. This is the main reason interfaces exist: they let parts of a program depend on a capability instead of on a particular class.
Default and static methods
Since Java 8 an interface can supply a default method, a method with a body marked default, which every implementing class inherits unless it overrides it. Default methods let an interface offer useful behavior built from its abstract methods, and let library designers add methods to an interface without breaking every class that already implements it. An interface can also have static methods, helpers called through the interface name, and, since Java 9, private methods that its default methods share.
public class Main {
public static void main(String[] args) {
Priced tube = new Part("700x25c inner tube", 899);
Priced service = new Service("wheel true", 2);
System.out.println(tube.receiptLine());
System.out.println(service.receiptLine());
System.out.println("Tax on 1000 cents: " + Priced.taxOn(1000));
}
}
interface Priced {
long priceCents();
String label();
default long taxCents() {
return taxOn(priceCents());
}
default String receiptLine() {
return String.format("%-22s %8s tax %6s", label(), cents(priceCents()), cents(taxCents()));
}
static long taxOn(long cents) {
return (cents * 8 + 50) / 100;
}
private static String cents(long c) {
return String.format("%d.%02d", c / 100, c % 100);
}
}
class Part implements Priced {
private final String name;
private final long cents;
Part(String name, long cents) { this.name = name; this.cents = cents; }
@Override public long priceCents() { return cents; }
@Override public String label() { return name; }
}
class Service implements Priced {
private final String job;
private final int hours;
Service(String job, int hours) { this.job = job; this.hours = hours; }
@Override public long priceCents() { return hours * 4000L; }
@Override public String label() { return job + " (" + hours + " h)"; }
}700x25c inner tube 8.99 tax 0.72 wheel true (2 h) 80.00 tax 6.40 Tax on 1000 cents: 80
What this code does
Part and Service implement only priceCents and label, yet both get taxCents and receiptLine from the interface's default methods. taxOn is a static method called as Priced.taxOn, and cents is a private helper the default methods share. Two hours of shop time at 40 dollars an hour is 80.00, with 6.40 tax.
An interface can also declare constants: any field in an interface is automatically public, static and final. Use this lightly; a constant usually belongs with the class or enum it describes.
Implementing several interfaces
A class can extend one class and implement several interfaces at once, listing them after implements and separating them with commas. A RentalBooking can be a Booking, Priced and also Comparable, the library interface that lets objects be sorted in a natural order. Comparable<RentalBooking> has one method, compareTo, which returns a negative number, zero or a positive number when this object comes before, equal to or after the other. The <RentalBooking> part is a type argument, which JAVA-120 explains with generics.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
RentalBooking[] rentals = {
new RentalBooking("Theo Park", "2027-04-10", 3),
new RentalBooking("Ana Ruiz", "2027-04-03", 1),
new RentalBooking("Mei Lin", "2027-04-06", 7),
};
Arrays.sort(rentals);
for (RentalBooking r : rentals) {
System.out.println(r.getDate() + " " + r.label() + " " + r.priceCents());
}
}
}
interface Priced {
long priceCents();
String label();
}
abstract class Booking {
private final String customer;
private final String date;
Booking(String customer, String date) { this.customer = customer; this.date = date; }
String getCustomer() { return customer; }
String getDate() { return date; }
}
class RentalBooking extends Booking implements Priced, Comparable<RentalBooking> {
private final int days;
RentalBooking(String customer, String date, int days) {
super(customer, date);
this.days = days;
}
@Override public long priceCents() { return 1500L * (days - days / 7); }
@Override public String label() { return getCustomer() + ", " + days + (days == 1 ? " day" : " days"); }
@Override
public int compareTo(RentalBooking other) {
return getDate().compareTo(other.getDate());
}
}2027-04-03 Ana Ruiz, 1 day 1500 2027-04-06 Mei Lin, 7 days 9000 2027-04-10 Theo Park, 3 days 4500
What this code does
RentalBooking extends one class and implements two interfaces, so it is a Booking, Priced and Comparable all at once. Its compareTo orders rentals by date, so Arrays.sort puts them in date order without being told how. Dates written as year-month-day sort correctly as text, which is one reason that layout is used.
Abstract class or interface?
The two tools overlap, and choosing between them is a design question. An abstract class is the better fit when the subclasses are truly kinds of the same thing and share state, such as every booking having a customer and a status. An interface is the better fit when you are describing a capability that unrelated classes can have, such as being priced, being comparable or being able to be printed on a tag. Because a class can have only one superclass, interfaces are also the only way to give a class several such capabilities.
| Abstract class | Interface | |
|---|---|---|
| Instance fields | Yes | No (only constants) |
| Constructors | Yes | No |
| Methods with bodies | Yes | Default, static and private methods |
| How many per class | One (extends) | Many (implements) |
| Best for | Kinds of one thing sharing state | A capability any class can have |
| Booking system example | Booking | Priced, Comparable |
A common, flexible design uses both: an interface for the capability, used as the type in most code, and an abstract class that implements part of it as a convenient starting point for subclasses. Java's own library does this, with the List interface and the AbstractList class.
Sealed classes and interfaces
Sometimes you want an abstract type to have exactly a known set of subtypes and no others. The booking system has two kinds of booking, repair and rental, and the rest of the program can be simpler if it knows there will never be a third it has not heard of. Java 17 added sealed classes and interfaces for this. A sealed type lists the classes permitted to extend or implement it, and each of those must itself be final, sealed or non-sealed.
public class Main {
public static void main(String[] args) {
Booking[] all = {
new RepairBooking("Ana Ruiz", "brake bleed"),
new RentalBooking("Theo Park", 3),
};
for (Booking b : all) {
System.out.println(b.customer() + ": " + b.kind());
}
}
}
sealed interface Booking permits RepairBooking, RentalBooking {
String customer();
String kind();
}
final class RepairBooking implements Booking {
private final String customer;
private final String job;
RepairBooking(String customer, String job) { this.customer = customer; this.job = job; }
@Override public String customer() { return customer; }
@Override public String kind() { return "repair: " + job; }
}
final class RentalBooking implements Booking {
private final String customer;
private final int days;
RentalBooking(String customer, int days) { this.customer = customer; this.days = days; }
@Override public String customer() { return customer; }
@Override public String kind() { return "rental: " + days + " days"; }
}Ana Ruiz: repair: brake bleed Theo Park: rental: 3 days
What this code does
Booking is a sealed interface that permits exactly two implementations, and both are final. Any other class that tried to implement Booking would not compile. Lesson 7 shows the payoff: a switch over a sealed type can check that every permitted case is handled.
When all the permitted classes are in the same file, as here, the permits list is optional, because javac can see them. Writing it anyway documents the design.
Try it yourself
An abstract method
Make Job abstract with an abstract method minutes(). Implement it in FlatRepair (always 20 minutes) and in TuneUp (60 minutes, plus 15 more if withWash is true).
The program should print flat repair: 20 min, tune-up: 75 min and Total: 95 min.
public class Main {
public static void main(String[] args) {
Job[] jobs = { new FlatRepair(), new TuneUp(true) };
int total = 0;
for (Job j : jobs) {
System.out.println(j.name() + ": " + j.minutes() + " min");
total += j.minutes();
}
System.out.println("Total: " + total + " min");
}
}
class Job {
String name() { return "job"; }
int minutes() { return 0; }
}
class FlatRepair extends Job {
@Override String name() { return "flat repair"; }
}
class TuneUp extends Job {
private final boolean withWash;
TuneUp(boolean withWash) { this.withWash = withWash; }
@Override String name() { return "tune-up"; }
}Try it yourself
A default method
Add a default method isExpensive() to the Priced interface that returns true when priceCents() is more than 10000.
The program should print brake pads: false and cargo bike rental: true.
public class Main {
public static void main(String[] args) {
Priced a = new Item("brake pads", 1650);
Priced b = new Item("cargo bike rental", 12000);
System.out.println(a.label() + ": false");
System.out.println(b.label() + ": false");
}
}
interface Priced {
long priceCents();
String label();
}
class Item implements Priced {
private final String name;
private final long cents;
Item(String name, long cents) { this.name = name; this.cents = cents; }
@Override public long priceCents() { return cents; }
@Override public String label() { return name; }
}Common mistakes
MistakeTrying to create an object of an abstract class with new.
InsteadCreate a concrete subclass; the abstract class only provides shared parts.
MistakeImplementing an interface method without public.
InsteadInterface methods are public, so the implementation must be public too.
MistakeGiving an interface instance fields to share state.
InsteadInterfaces cannot hold per-object state; use an abstract class for shared fields.
MistakeUsing an abstract class for a capability unrelated classes share.
InsteadUse an interface, which any class can implement alongside its superclass.
MistakeAdding a new abstract method to an interface many classes already implement.
InsteadAdd it as a default method so existing classes keep compiling.
Summary and key terms
- An abstract class cannot be instantiated; it can have fields, constructors and finished methods, and its abstract methods have no body and must be implemented by concrete subclasses.
- An interface lists what a type can do; a class implements it by providing the methods, which are public.
- A class extends one class but can implement many interfaces, and an interface name can be used as a type so code depends on a capability rather than a class.
- Default methods give interfaces shared behavior, static methods are helpers called through the interface name and private methods help the defaults.
- Comparable lets objects sort in a natural order through compareTo.
- Choose an abstract class for kinds of one thing with shared state and an interface for capabilities.
- A sealed class or interface lists the only types permitted to extend or implement it.
- Abstract class
- A class that cannot be instantiated and may declare abstract methods.
- Abstract method
- A method with no body that subclasses must implement.
- Concrete class
- A class that is not abstract and can be instantiated.
- Interface
- A type that lists methods a class promises to provide.
- implements
- The keyword a class uses to declare the interfaces it provides.
- Default method
- An interface method with a body that implementing classes inherit.
- Comparable
- A library interface whose compareTo method defines a natural order.
- compareTo
- A method returning negative, zero or positive to order two objects.
- Sealed
- Describes a class or interface that permits only listed subtypes.
- permits
- The clause listing the subtypes a sealed type allows.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Can an abstract class have a constructor?
Show answer
Yes; it runs when a subclass constructor calls super(...).
How many interfaces can a class implement?
Show answer
Any number.
Why must Part's priceCents be public?
Show answer
Interface methods are public, and an implementation cannot be less accessible.
What does a default method let an interface do?
Show answer
Provide a method body that every implementing class inherits unless it overrides it.
What must the classes permitted by a sealed interface be?
Show answer
final, sealed or non-sealed.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.