DEV Community

Bala Murugan
Bala Murugan

Posted on

Encapsulation in Java

What is Encapsulation:

Encapsulation is the process of binding data (variables) and methods into a single unit called a class. It is used to protect data from unauthorized access.

Encapsulation is achieved by:

  1. Declaring variables as private.
  2. Providing public getter and setter methods to access and update the data.

Why Use Encapsulation:

  • Provides data security.
  • Prevents unauthorized access.
  • Improves maintainability.
  • Provides better control over data.
  • Follows the principle of data hiding.
class Student {

    private String name;

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

    public String getName() {
        return name;
    }
}

public class Main {

    public static void main(String[] args) {

        Student s = new Student();

        s.setName("Bala");

        System.out.println(s.getName());
    }
}


Enter fullscreen mode Exit fullscreen mode
Output:

Bala

Enter fullscreen mode Exit fullscreen mode

Access Modifiers in Java

Access modifiers control the visibility and accessibility of classes, variables, methods, and constructors.

There are four types of access modifiers:

  1. Public
  2. Private
  3. Protected
  4. Default

  5. Public

A public member can be accessed from anywhere in the program

public class Demo {

    public int age = 22;
}


Enter fullscreen mode Exit fullscreen mode

Access:

  • Same class
  • Same package
  • Different package
  • Subclass
  1. Private

A private member can be accessed only within the same class.

class Demo {

    private int age = 22;
}


Enter fullscreen mode Exit fullscreen mode

Access:

  • Same class
  • Same package
  • Different package
  • Subclass
  1. Protected

A protected member can be accessed within the same package and by subclasses.

class Demo {

    protected int age = 22;
}


Enter fullscreen mode Exit fullscreen mode

Access:

  • Same class
  • Same package
  • Different package
  • Subclass
  1. Default

When no access modifier is specified, it becomes default access.

class Demo {

    int age = 22;
}

Enter fullscreen mode Exit fullscreen mode

Access:

  • Same class
  • Same package
  • Different package
  • Subclass (different package)

Top comments (0)