DEV Community

Cover image for Understanding Encapsulation in Object-Oriented Programming
Edwin Kinyao
Edwin Kinyao

Posted on

Understanding Encapsulation in Object-Oriented Programming

Encapsulation in Object-Oriented Programming

Encapsulation is a fundamental object-oriented programming concept that involves bundling data (fields) and methods (functions) that operate on the data within a single unit, typically a class. It restricts direct access to some of the object's components, making it easier to maintain and secure the code.

Benefits of Encapsulation

  1. Data Hiding: Internal state is hidden from the outside world, and access is controlled through methods (getters and setters).
  2. Improved Code Maintainability: Changes to fields or methods can be made without affecting external code that uses the class.
  3. Enhanced Security: By restricting direct access to fields, we can validate and protect data from invalid states.

Code Example: Encapsulation in Action

// Encapsulation refers to restricting access of a class from the outside world
public class Person {
    private String name;
    private String profession;
    private double height;
    private int ID;
    private int age;

    // Constructor
    public Person(String name, String profession, double height, int iD, int age) {
        this.name = name;
        this.profession = profession;
        this.height = height;
        ID = iD;
        this.age = age;
    }

    // Getters and setters for accessing private fields
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getProfession() {
        return profession;
    }
    public void setProfession(String profession) {
        this.profession = profession;
    }
    public double getHeight() {
        return height;
    }
    public void setHeight(double height) {
        this.height = height;
    }
    public int getID() {
        return ID;
    }
    public void setID(int iD) {
        ID = iD;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    // Main method to demonstrate encapsulation
    public static void main(String[] args) {
        Person myPerson = new Person("Robert", "doctor", 130.4, 39, 23);

        // Accessing private fields through getter methods
        System.out.println(myPerson.getName());
        System.out.println(myPerson.getProfession());
        System.out.println(myPerson.getID());
        System.out.println(myPerson.getAge());
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation of the Code

Private Fields

The fields name, profession, height, ID, and age are declared as private. This makes them inaccessible directly from outside the class.

Getters and Setters

Public methods like getName(), setName(), getProfession(), and others act as controlled access points for the private fields. These methods allow external code to retrieve and modify the private data securely.

Constructor

The constructor initializes the fields when an object of the class Person is created. This ensures that the object starts in a valid state.

Main Method

The main method demonstrates how encapsulation is used. The private fields are accessed indirectly through the getter methods.


Benefits in the Example

  1. Data Protection:

    • The private fields cannot be accessed or modified directly, preventing accidental or malicious changes.
  2. Controlled Access:

    • By using setters, you can include validation logic to ensure only valid data is set. For example:
     public void setAge(int age) {
         if (age > 0) {
             this.age = age;
         } else {
             System.out.println("Age must be positive.");
         }
     }
    
  3. Code Flexibility:

    • If the implementation of fields changes (e.g., adding derived fields), external code using the class remains unaffected.

This example illustrates how encapsulation ensures that the Person class maintains integrity and hides its implementation details while providing a controlled interface for interaction.

Top comments (0)