Encapsulation In Java

The concept of encapsulation in Java plays a crucial role in object-oriented programming by safeguarding data and limiting direct access to class members. This section will delve into the mechanics of encapsulation and the utilization of access modifiers to accomplish this goal.

What is Encapsulation in Java?

Encapsulation involves bundling data and methods within a unified unit. An analogy to encapsulation is a capsule that combines multiple medications into a single entity.

To establish a fully encapsulated class, we designate all the data members as private. Subsequently, we implement setter and getter functions to assign and retrieve the data securely. This approach conceals the implementation details, ensuring controlled access and safeguarding the data against unauthorized alterations.

In Java, a fully encapsulated class can be achieved by declaring all data members of the class as private. This approach allows us to utilize setter and getter methods to assign and retrieve the data within the class.

Why Use Encapsulation in Java?

The following are the important reasons to use the encapsulation:

  • Encapsulation helps to protect data and control access to it.
  • It protects sensitive data from being access directly.
  • It hides unnecessary data from the user of a class, and only shows the functionality of a class.
  • Changes can be made internally without affecting the external interface.
  • It is easier to scale applications because it provides flexibility to add or modify features without impacting the entire codebase.
  • Encapsulated classes can be reused across projects.
  • Example of Encapsulation

Let's explore an illustration of encapsulation by utilizing a class that contains a single field along with its corresponding setter and getter functions.

Fully Encapsulated Class

Presented here is the Student class, featuring a private field for the name attribute alongside public methods for retrieving and setting the name, namely getName and setName.

Example

//A Java class which is a fully encapsulated class.  

//It has a private data member and getter and setter methods.  

package com.example;  

public class Student{  

//private data member  

private String name;  

//getter method for name  

public String getName(){  

return name;  

}  

//setter method for name  

public void setName(String name){  

this.name=name  

}  

}

Test Class

In this example, a Main class is utilized to instantiate a Student object, assign a name to it, and then display the name.

Example

Example

//A Java class to test the encapsulated class.  

package com.example;  

class Main {  

public static void main(String[] args) {  

//creating an instance of the encapsulated class  

Student s=new Student();  

//setting value in the name member  

s.setName("vijay");  

//getting value of the name member  

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

}  

}

Output:

Read-Only Class

The Student class includes a private field called college, with a sole method getCollege for accessing the college information.

Within this class, the college value is immutable and cannot be modified externally.

Example

//A Java class which has only getter methods.

public class Student{

//private data member

private String college="AKG";

//getter method for college

public String getCollege(){

return college;

}

}

In this scenario, it is not permissible to alter the value of the college data attribute, specifically set as "AKG".

Example

s.setCollege("KITE");//will render compile time error

Write-Only Class

A class named Student contains a private field named college, with a method setCollege to modify the college field.

Example

//A Java class which has only setter methods.

public class Student{

//private data member

private String college;

//getter method for college

public void setCollege(String college){

this.college=college;

}

}

Within this class, it is possible to assign a value to the variable "college," yet its value cannot be accessed externally.

Currently, it is not possible to retrieve the value of the college; instead, you can solely modify the value of the college data member.

Example

System.out.println(s.getCollege());//Compile Time Error, because there is no such method

System.out.println(s.college);//Compile Time Error, because the college data member is private. 

//So, it can't be accessed from outside the class

Since the data member is declared as private, it is not accessible directly from external sources beyond the class scope.

Real-Life Example of Encapsulation

In this illustration, we showcase the application of encapsulation through a practical case involving a bank account. The data attributes are kept private, with external access facilitated by publicly available getter and setter functions.

Example

//A Account class, which is a fully encapsulated class.    

//It has a private data member and getter and setter methods.    

class Account {    

//private data members    

private long acc_no;    

private String name,email;    

private float amount;    

//public getter and setter methods    

public long getAcc_no() {    

    return acc_no;    

}    

public void setAcc_no(long acc_no) {    

    this.acc_no = acc_no;    

}    

public String getName() {    

    return name;    

}    

public void setName(String name) {    

    this.name = name;    

}    

public String getEmail() {    

    return email;    

}    

public void setEmail(String email) {    

    this.email = email;    

}    

public float getAmount() {    

    return amount;    

}    

public void setAmount(float amount) {    

    this.amount = amount;    

}    

}    

//A Java class to test the encapsulated class Account.    

public class Main {    

public static void main(String[] args) {    

    //creating instance of Account class    

    Account acc=new Account();    

    //setting values through setter methods    

    acc.setAcc_no(7560504000L);    

    acc.setName("Sonoo Jaiswal");    

    acc.setEmail("sonoojaiswal@example.com");    

    acc.setAmount(500000f);    

    //getting values through getter methods    

    System.out.println(acc.getAcc_no()+" "+acc.getName()+" "+acc.getEmail()+" "+acc.getAmount());    

}    

}

Output:

Output

7560504000 Sonoo Jaiswal sonoojaiswal@example.com 500000.0

The Java Bean class serves as a prime illustration of a class that is completely encapsulated.

Advantages of Encapsulation in Java

Encapsulation offers various advantages, especially ensuring code organization and better design.

  • Data Protection: Encapsulation restricts direct access to fields of a class, preserving the integrity of data by allowing controlled access through getter and setter methods.
  • Enhanced Security: By hiding internal implementation details and exposing only necessary functionality, encapsulation makes code less vulnerable to unintended interference and misuse.
  • Improved Maintainability: Changes to implementation can be made without affecting external code, as long as the public interface remains consistent.
  • Increased Flexibility: Encapsulation allows developers to modify or extend the behavior of objects without altering the code that uses them.
  • Encourages Modularity: Encapsulation helps in dividing the program into distinct modules, making it easier to debug and test.
  • Promotes Abstraction: It simplifies how data is handled by hiding unnecessary details from users of a class.
  • Disadvantages of Encapsulation in Java

Several disadvantages of Encapsulation in Java are as follows:

  • Increase Code Complexity: It increases code complexity due to the getter and setter methods for every field. It leads to longer code.
  • Decrease Performance: It decreases performance by invoking the getter and setter methods instead of directly accessing variables. It may have a slight impact on performance.
  • Impractical for Small-Scale Programs: In small-scale applications, implementing encapsulation might feel excessive or unnecessary.
  • Mismanagement of Setters and Getters: Poorly implemented getter and setter methods can disrupt the concept of encapsulation if they expose too much or allow unintended behavior.
  • Learning Curve: It can be challenging for bingers because understanding and correctly applying encapsulation may slow down initial progress.

Input Required

This code uses input(). Please provide values below: