Compare and contrast abstract classes and interfaces in Java. When would you choose to use one over the other?
Java interview question for Advanced practice.
Answer
Abstract classes and interfaces are both mechanisms in Java for achieving abstraction, but they have key differences that make them suitable for different scenarios. Abstract Class: State: Can have instance variables (state). Constructors: Can have constructors (which are called by subclass constructors). Methods: Can have a mix of abstract methods (no implementation) and concrete methods (with implementation). Inheritance: A class can only extend one abstract class. Relationship: Establishes a strong 'is-a' relationship, often used for a group of closely related objects. Interface: State: Cannot have instance variables (only public static final constants). Constructors: Cannot have constructors. Methods: Traditionally, only abstract method signatures. Since Java 8, can also have default and static methods with implementations. Inheritance: A class can implement multiple interfaces. Relationship: Defines a 'can-do' capability or a contract that unrelated classes can fulfill. When to Choose Which: Choose an Abstract Class when: You want to share code (concrete methods) or state (instance fields) among several closely related classes. You expect the base requirements to change over time, as you can add new concrete methods to an abstract class without breaking existing subclasses. Choose an Interface when: You expect that unrelated classes will implement the contract (e.g., Comparable, Serializable). You want to define the behavior of a data type, but you are not concerned about who implements its behavior. You want to take advantage of multiple inheritance of type.
Explanation
Since Java 8, interfaces can contain default and static methods with implementations, which allows for adding new functionality to existing interfaces without breaking implementing classes. However, they still cannot hold instance state.