Encapsulation vs Abstraction
Why This Is Asked
These are two of the four pillars of OOP. Candidates often confuse them. Interviewers look for the distinction between “hiding data” (Encapsulation) and “hiding complexity” (Abstraction).
Key Concepts
- Encapsulation: Bundling data and methods into a single unit (class) and restricting direct access to the state (private fields/public properties).
- Abstraction: Showing only essential features of an object and hiding the background details or implementation logic.
- Abstraction is about what an object does; Encapsulation is about how it does it and protecting its internal state.
Answers by Technology
+ Add VariantExpected Answer (.NET 10 / C# 14)
While related, Encapsulation and Abstraction solve different problems:
- Encapsulation is about Hiding Data. It uses access modifiers (
private,protected,internal) and properties to protect the internal state of an object. It ensures that an object is in control of its own data. - Abstraction is about Hiding Complexity. It uses interfaces and abstract classes to define what an object does without revealing how it does it.
Why It Matters
In .NET, these principles allow us to build systems that are easy to maintain and test. By using interfaces (Abstraction), we can swap implementations (e.g., using a Mock database for tests). By using private fields and public properties (Encapsulation), we ensure that invalid data cannot be assigned to our objects.
Code Example
// Abstraction: I don't care HOW the message is sent, just that it is.
public interface IMailService
{
void Send(string message);
}
// Encapsulation: The balance is private and can only be changed via methods.
public class BankAccount
{
private decimal _balance; // Hidden data
public void Deposit(decimal amount)
{
if (amount > 0) _balance += amount; // Logic protected
}
}
Common Mistakes
- Public Fields: Exposing raw fields directly violates encapsulation. Always use Properties.
- Over-Abstraction: Creating interfaces for every single class, even when there’s only one possible implementation, leads to “Interface Bloat.”
Follow-up Questions
- How do Properties in C# support encapsulation? (Answer: They allow you to add validation logic in the
setaccessor while keeping the field private). - Can you have Abstraction without Encapsulation? (Answer: Technically yes, but you lose the safety of the object’s internal state).
Expected Answer (Java 26)
In Java, these two OOP pillars have distinct roles:
- Encapsulation is about Data Hiding. It involves making class fields
privateand providing access throughpublicgetter and setter methods. It protects the internal state from unauthorized modification. - Abstraction is about Complexity Hiding. It uses
interfacesandabstract classesto define a contract for what a class should do, without specifying how.
Why It Matters
These principles are the foundation of clean, modular Java code. Encapsulation ensures that an object maintains its validity (e.g., an Age field cannot be negative). Abstraction allows you to write code that depends on behaviors (e.g., List) rather than specific implementations (e.g., ArrayList), making it easy to change implementations later.
Code Example
// Abstraction: Focus on the 'what'
public interface Shape {
double area();
}
// Encapsulation: Protect the 'how' and the data
public class Circle implements Shape {
private double radius; // Hidden data
public Circle(double radius) {
if (radius > 0) this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
Common Mistakes
- Direct Field Access: Marking fields as
publicorprotectedwhen they should beprivate. - Returning Mutable Objects: A getter that returns a reference to a private
Liststill allows external modification. UseCollections.unmodifiableList().
Follow-up Questions
- How do Records improve encapsulation in Java? (Answer: Records provide a concise way to create immutable data carriers with built-in private fields and public accessors).
- Abstract Class vs Interface? (Answer: Abstract classes can have state and non-public methods; Interfaces are primarily for defining behavior contracts).
Expected Answer (PHP 8.5)
In PHP, these OOP principles are implemented using visibility modifiers and interfaces:
- Encapsulation: Using
private,protected, andpublicto hide an object’s internal state. PHP 8.x’s Constructor Property Promotion makes this very concise. - Abstraction: Using
interfaceandabstract classto define the “what” of an object.
Why It Matters
Encapsulation prevents the “Spaghetti Code” where any part of the application can reach in and change an object’s state. Abstraction allows you to use Dependency Injection to write code that is decoupled from specific implementations (e.g., MailerInterface instead of SmtpMailer).
Code Example
// Abstraction
interface Gateway {
public function pay(int $amount): void;
}
// Encapsulation
class StripeGateway implements Gateway {
// Constructor Property Promotion (PHP 8.0+)
public function __construct(
private string $apiKey // Capsule: Private data
) {}
public function pay(int $amount): void {
// Implementation hidden
}
}
Common Mistakes
- Using
publicproperties by default: Always favorprivateorprotectedwith getters/setters (orreadonlyin PHP 8.1+) to maintain control. - Missing return types: Not using PHP 7/8’s type system reduces the effectiveness of abstraction.
Follow-up Questions
- What are ‘Readonly’ properties? (Answer: Introduced in PHP 8.1, they can only be set once, providing a form of immutable encapsulation).
- Can a trait implement an interface? (Answer: No, but a class using a trait can).