In Java, when should you use an interface and when an abstract class?
TechnicalEnterprise ArchitectSolution ArchitectIT ArchitectIn Java, I choose an interface when I want to define a contract for classes without enforcing any implementation details. Interfaces are ideal for defining behaviors that can be shared across different classes, especially when those classes are not related by inheritance. For instance, if I have multiple classes like Car and Boat that need to implement a Drivable interface, they can do so without sharing a common parent class.
On the other hand, I use an abstract class when I want to provide a common base with shared code and some abstract methods that subclasses must implement. This is useful when I have a clear hierarchy. For example, if I have a base class Vehicle that provides common properties like speed and fuel, I can extend it with Car and Truck classes that implement specific behaviors.
The key differences are that interfaces support multiple inheritance while abstract classes do not. However, abstract classes can have state and constructors, which interfaces cannot. Therefore, I choose interfaces for flexibility and abstract classes for shared functionality.