Video in progress
What do you base the choice on between an abstract class and an interface?
Abstract class / Interface — Inheritance: Only one extends / Many implements; State (instance fields): Yes / No, only constants; Constructor: Yes / No; Methods: Any access level / public (or a private helper); Meaning: "This is a ..." / "This can ..."
📖 Answer
| Abstract class | Interface | |
|---|---|---|
| Inheritance | Only one extends |
Many implements |
| State (instance fields) | Yes | No, only constants |
| Constructor | Yes | No |
| Methods | Any access level | public (or a private helper) |
| Meaning | "This is a ..." | "This can ..." |
A practical example: Comparable, Serializable and AutoCloseable are interfaces, because String, LocalDate and your own Order class can all adopt them, even though they have nothing in common.
AbstractList, on the other hand, is an abstract class: it provides many of the List interface's methods (indexOf, iterator, equals) ready-made, and you only write get and size.
In modern Java many teams do this: an interface for the external contract, and next to it an optional abstract class to collect repeated code. Since default methods arrived, abstract classes are needed less, but if you need state, you still end up with one.
Sign up to mark studied questions and save your progress.