CSE Roadmap

Core tier · about 2 hours · 6 parts

Part 4 of 6 · 2 min read

Interface or abstract class

EJ prefers interfaces for types.

Java offers two ways to define a type with several implementations. An abstract class can hold some fields and code and leaves the rest to subclasses. An interface lists the methods and, since Java 8, may give some of them default code.

EJ Item 20 says to prefer interfaces. Its reasons, in my own words: - A class may extend only one parent, so an abstract class forces implementers into one branch of the hierarchy. A class may implement any number of interfaces. - Existing classes can be fitted with a new interface by adding the methods and an implements clause. They cannot in general be fitted with a new abstract parent. The standard Comparable and Iterable interfaces were added to old classes that way. - Interfaces suit mixins: optional abilities that a class adds to its main type. Comparable says "my instances have an order". - Interfaces allow types that are not strict hierarchies. A singer and a songwriter are different types, and one class can be both.

Abstract classes still have a place. When much of the code is shared, a class may supply the common parts and let subclasses fill in a few steps. Level 4 meets this as the template method. Interfaces may also provide default methods, but EJ cautions that adding a method to a published interface can break existing implementers, so interfaces need careful design.

A rule of thumb from the above (common practice): start with an interface. Add an abstract class only when several implementations really share state or most of their code.

Abstract class

An abstract class is a class that cannot be instantiated on its own. It may hold fields and code, and it declares abstract methods that subclasses must provide.

Example: an abstract Vehicle with a shared plate number and an abstract wheels() method that Car and Bike fill in.

Check yourself: 1. Why can a class implement many interfaces but extend one class? 2. What is a mixin? 3. When might an abstract class still be the better choice?