Encapsulation vs Abstraction in Java

1. Introduction

Encapsulation and abstraction are two of the four fundamental OOP concepts in Java. Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. It's a protective barrier that keeps the data and code safe within the class itself. Abstraction, on the other hand, is a concept of hiding the complex reality while showing only the necessary parts to the user. It can be achieved using abstract classes and interfaces.

2. Key Points

1. Encapsulation hides the internal state and requires all interaction to be performed through an object's methods.

2. Abstraction hides the implementation details and shows only the necessary functionality to the user.

3. Encapsulation is achieved in Java using access modifiers; private, protected, and public.

4. Abstraction is achieved in Java using abstract classes and interfaces.

3. Differences

Encapsulation Abstraction
Concerned with protecting object state by hiding the details of the data. Concerned with hiding the implementation details and showing only the necessary features of an object.
Implemented using private or protected modifiers with public getters/setters. Implemented using abstract classes and interfaces.
Controls the access to the data and methods to prevent unintended interference and misuse of data. Reduces complexity by hiding the unnecessary detail and showing only the required functionality.

4. Example

// Example of Encapsulation
public class Employee {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

// Example of Abstraction
public abstract class Animal {
    public abstract void makeSound();

    public void eat() {
        System.out.println("Animal is eating");
    }
}

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Woof woof");
    }
}

Output:

// No specific output, it is a conceptual demonstration.

Explanation:

1. The Employee class uses encapsulation by keeping its name field private and providing public getter and setter methods.

2. The Animal class demonstrates abstraction by providing a method eat that has an implementation and an abstract method makeSound that does not have an implementation.

5. When to use?

- Use encapsulation to protect the integrity of an object by preventing outsiders from setting the internal data into an inconsistent or invalid state.

- Use abstraction when you want to hide the complex implementation logic and expose only the necessary and relevant information and behavior.

Comments