DEV Community

PRIYA K
PRIYA K

Posted on

Encapsulation in Java

read gfg,w3schools,tutorialpoint

Encapsulation in Java is the process of bundling data (variables) and the methods that operate on that data into a single unit, typically a class. It is one of the four fundamental principles of Object-Oriented Programming (OOP). The other three are inheritance, polymorphism, and abstraction.

Encapsulation refers to the bundling of fields and methods inside a single class.
It prevents outer classes from accessing and changing fields and methods of a class. This also helps to achieve data hiding.

Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

It restricts direct access to data by hiding implementation details. This ensures controlled interaction with the data through defined methods.
This encapsulation mechanism protects the internal state of the Programmer object and allows for better control and flexibility in how the name attribute is accessed and modified.

Achieved using access modifiers like private, protected, and public.
Improves data security by allowing validation through getters and setters.
Enhances code maintainability by isolating changes within the class.
Enter fullscreen mode Exit fullscreen mode

we use the encapsulation and use getter (getName) and setter (setName) method which are used to show and modify the private data.

This encapsulation mechanism protects the internal state of the Programmer object and allows for better control and flexibility in how the name attribute is accessed and modified.

to make sure that "sensitive" data is hidden from users. To achieve this, you must:
declare class variables/attributes as private
provide public get and set methods to access and update the value of a private variable

encapsulation vs data hiding
Encapsulation refers to the bundling of related fields and methods together. This can be used to achieve data hiding. Encapsulation in itself is not data hiding.

Why Encapsulation?

In Java, encapsulation helps us to keep related fields and methods together, which makes our code cleaner and easy to read.
It helps to control the values of our data fields
Better control of class attributes and methods
Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method)
Flexible: the programmer can change one part of the code without affecting other parts
Increased security of data
Enter fullscreen mode Exit fullscreen mode

Get and Set
private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods.

The get method returns the variable value, and the set method sets the value.
The set method takes a parameter (newName) and assigns it to the name variable.
The this keyword is used to refer to the current object.

However, as the name variable is declared as private, we cannot access it from outside this class:

Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case.

Benefits of Encapsulation
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.

Java Encapsulation: Read-Only Class
A read-only class can have only getter methods to get the values of the attributes, there should not be any setter method.

Java Encapsulation: Write-Only Class
A write-only class can have only setter methods to set the values of the attributes, there should not be any getter method.

The getter and setter methods provide read-only or write-only access to our class fields. For example,

getName() // provides read-only access
setName() // provides write-only access

It helps to decouple components of a system. For example, we can encapsulate code into multiple bundles.

These decoupled components (bundle) can be developed, tested, and debugged independently and concurrently. And, any changes in a particular component do not have any effect on other components.
We can also achieve data hiding using encapsulation.
if we change the variable into private,then the access to these fields is restricted. and they are kept hidden from outer classes. This is called data hiding.

How to Implement Encapsulation
To achieve encapsulation in Java, you follow two main steps:
1.Declare variables as private: This hides the data from direct access by any code outside the class
2.Provide public getter and setter methods: These methods allow other classes to read or modify the private variables in a controlled and safe manner.

Achieving Encapsulation in Java
Declare the variables of a class as private or Private data members.
Provide public setter and getter methods to modify and view the variables values.

Key Rules:
Declare data as private: Hide the class data so it cannot be accessed directly from outside the class.
Use getters and setters: Keep variables private and provide public getter and setter methods for controlled access and safe modification, often with validation.
Apply proper access modifiers: Use private for data hiding and public for methods that provide access.

Advantages of Encapsulation
Data Hiding: Encapsulation restricts direct access to class variables, protecting sensitive data from unauthorized access.
Improved Maintainability: Changes to internal implementation can be made without affecting external code that uses the class.
Enhanced Security: Encapsulation allows validation and control over data, preventing invalid or harmful values from being set.
Code Reusability: Encapsulated classes can be reused in different programs without exposing internal logic.
Better Modularity:Encapsulation promotes organized, modular code by keeping data and methods together within a class.

Disadvantages of Encapsulation
Increased Code Complexity: Writing getter and setter methods for every variable can make the code longer and slightly more complex.
Performance Overhead: Accessing data through methods instead of directly can introduce a minor performance cost, especially in performance-critical applications.
Less Flexibility in Some Cases: Over-restricting access to class members may limit the ability of other classes to extend or use the class efficiently.

Data Hiding vs Encapsulation
*Data Hiding *
Definition: Restricting direct access to data to protect it from unauthorized use.
Focus:Security of data

Purpose:Prevents misuse and accidental modification of data
How it is achieved:Using access modifiers (private, protected)

Involves methods:No (mainly focuses on data)

Scope:Narrow concept

Dependency:Independent concept

Example :private int balance;

Encapsulation
Definition:Wrapping data and methods into a single unit (class)
Focus:Structure and design
Purpose:Improves modularity and maintainability
How it is achieved:Using classes, methods, and access modifiers
Involves methods:Yes (includes both data and methods)
Scope:Broader concept
Dependency:Encapsulation may use data hiding.for better security but it is not mandatory.
Example:
class Account { private int balance; public getBalance(); }

Example

public class Person {
    // 1. Private data members
    private String name;

    // 2. Public Getter method
    public String getName() {
        return name;
    }

    // 3. Public Setter method
    public void setName(String newName) {
        this.name = newName;
    }
}
Enter fullscreen mode Exit fullscreen mode

name is private, it cannot be accessed directly; instead, it must be accessed via getName() and modified via setName()

Data Hiding
Data hiding is a way of restricting the access of our data members by hiding the implementation details. Encapsulation also provides a way for data hiding.
We can use access modifiers to achieve data hiding. For example,
Example 2: Data hiding using the private specifier

class Person {
  // private field
  private int age;
  // getter method
  public int getAge() {
    return age;
  }
  // setter method
  public void setAge(int age) {
    this.age = age;
  }
}
class Main {
  public static void main(String[] args) {
    // create an object of Person
    Person p1 = new Person();
    // change age using setter
    p1.setAge(24);
    // access age using getter
    System.out.println("My age is " + p1.getAge());
  }
}
Enter fullscreen mode Exit fullscreen mode

Output
My age is 24

In the above example, we have a private field age. Since it is private, it cannot be accessed from outside the class.

In order to access age, we have used public methods: getAge() and setAge(). These methods are called getter and setter methods.

Making age private allowed us to restrict unauthorized access from outside the class. This is data hiding.

If we try to access the age field from the Main class, we will get an error.

// error: age has private access in Person
p1.age = 24;

Top comments (0)