Object-oriented programming · interview question
In modern Java (8+), when would you choose an abstract class over an interface? Compare the two.
0 words · aim for 40+
Answer and explanation
Correct answer
An interface defines a contract. A class can implement many interfaces, and since Java 8 interfaces can have default and static methods (Java 9 added private methods), but they can't hold instance state or constructors, and their fields are implicitly public static final constants.
An abstract class can have instance fields, constructors, protected members and a partial implementation, but a class can extend only one. Choose an abstract class when related classes share state or a template of behavior (for example an AbstractRepository with common fields and a template method). Choose an interface to define a capability across unrelated types (Comparable, Runnable) or when you need multiple inheritance of type. A common design is both: an interface for the contract plus an abstract skeletal implementation, like List and AbstractList.
Key points:
- A class can implement many interfaces but extend only one class
- Interfaces can have default/static methods (Java 8+) but no instance state
- Abstract classes can have fields, constructors and protected members
- Use an abstract class for shared state or behavior among related classes
- Use an interface for a capability or contract across unrelated types
Why
Mentioning the interface + skeletal implementation pattern (List/AbstractList) is a strong signal.
References
- The Java Language Specification, Java SE 21
- Joshua Bloch, Effective Java, 3rd ed. (2018)
Test yourself on Object-oriented programming
A free test with instant, explained results. No account needed.
More Object-oriented programming questions
- What happens if a subclass does not implement all abstract methods from its abstract superclass?
- What does the 'this' keyword refer to within an instance method of a class?
- Which Java keyword would you use to declare an abstract class in Java?
- Which statement correctly creates an instance of the 'Product' class?
- How does using interfaces in Java promote flexibility in application design?
- In Java, why might composition be preferred over inheritance when designing a class to calculate discounts for…