Abstract Classes vs Interfaces (When to Use Which)
1Concept
Abstract classes provide a common base with state (instance fields) and partial implementation for closely related classes (IS-A relationship). Interfaces define pure behavioral contracts with no instance state for potentially unrelated classes (CAN-DO relationship). Since Java 8/9, interfaces can have default, static, and private methods.
2Architecture Diagram
Abstract Class (Base): [ Shape ] (fields: color, x, y) ---> [ Circle ] (IS-A Shape) Interface (Contract): [ Serializable, Exportable ] ---> [ Circle ] (CAN-DO Export)
3Code Example
Core Java
public class AbstractionDemo {
abstract static class CloudResource {
protected String resourceId;
public CloudResource(String resourceId) { this.resourceId = resourceId; }
public abstract void provision();
}
interface Monitorable {
void collectMetrics();
}
static class VirtualMachine extends CloudResource implements Monitorable {
public VirtualMachine(String id) { super(id); }
@Override
public void provision() {
System.out.println("VM " + resourceId + " allocated on Hypervisor.");
}
@Override
public void collectMetrics() {
System.out.println("VM " + resourceId + " CPU utilization: 24%");
}
}
public static void main(String[] args) {
VirtualMachine vm = new VirtualMachine("i-098234fed");
vm.provision();
vm.collectMetrics();
}
}4Expected Output
VM i-098234fed allocated on Hypervisor. VM i-098234fed CPU utilization: 24%
5Key Takeaways
- ✓Use Abstract Classes when sharing state (fields) or protected helper methods.
- ✓Use Interfaces to define loose contracts across unrelated hierarchies.
- ✓A class can implement multiple interfaces, but extend only ONE class.