Encapsulation and abstraction both involve hiding, but different things: encapsulation hides data behind an access boundary; abstraction hides implementation behind a simple interface. Access modifiers enforce encapsulation, while abstract classes and interfaces are the tools of abstraction.
An abstract class can have both implemented and unimplemented (abstract) methods and holds state; a class extends only one. An interface is a pure contract of method signatures (traditionally no implementation, no state); a class can implement many. Use an abstract class for shared base behaviour, an interface for a capability.
Access modifiers
| Modifier | Visible to |
|---|---|
| private | the class only |
| protected | the class and its subclasses |
| public | everyone |
| default/package | the same package (language-dependent) |
- Decide between them by intent: abstract class = 'is-a' with shared code (single inheritance); interface = 'can-do' capability that many unrelated classes can implement (multiple).
- Encapsulation in practice: make fields private and expose public getters/setters, so you can validate and change internals without breaking callers.
- An abstract class can mix implemented and abstract methods and can hold state; a class can extend only one.
- An interface is a contract of method signatures (capability) that a class implements; a class can implement many.
- Choose an abstract class for shared base behaviour, an interface to declare a capability across unrelated classes.
- Making fields private prevents outside code from putting the object into an invalid state.
- Getters/setters let you validate inputs, make fields read-only, or log access.
- And you can change the internal representation later without breaking the public interface.
- Traditionally a class can extend one abstract class but implement many interfaces.
- Encapsulation (data hiding) and abstraction (implementation hiding) are distinct — don't merge them.
- Modern languages blur the line (interfaces can have default methods), but the intent distinction still holds.