c2cedge
LibraryCS Fundamentals › Ch 18
CS Fundamentals · D — Object-Oriented Programming

Abstraction, Encapsulation & Interfaces

Hiding the right things is half of good design. Access modifiers, abstract classes vs interfaces, and why we encapsulate are steady interview fare.

Test weight: HighAsked by: All recruitersDifficulty: Medium

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.

Abstract class vs interface

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

ModifierVisible to
privatethe class only
protectedthe class and its subclasses
publiceveryone
default/packagethe same package (language-dependent)
⚡ The edge
  • 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.
Worked example
'What is the difference between an abstract class and an interface?'
  1. An abstract class can mix implemented and abstract methods and can hold state; a class can extend only one.
  2. An interface is a contract of method signatures (capability) that a class implements; a class can implement many.
  3. Choose an abstract class for shared base behaviour, an interface to declare a capability across unrelated classes.
Worked example
'Why do we use encapsulation (getters/setters)?'
  1. Making fields private prevents outside code from putting the object into an invalid state.
  2. Getters/setters let you validate inputs, make fields read-only, or log access.
  3. And you can change the internal representation later without breaking the public interface.
⚠ Watch out
  • 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.
Practice this — take a timed mock →
1,300+ questions, scored, with a weak-area report.
Know who's ready. Not who finished.
HomeLibraryPrivacyTerms