Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Java Encapsulation Explained: Secure Data Hiding & Control

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.

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.

To achieve encapsulation in Java −

Example

Following is an example that demonstrates how to achieve Encapsulation in Java −

/* File name : EncapTest.java */
public class EncapTest {
   private String name;
   private String idNum;
   private int age;

   public int getAge() {
      return age;
   }

   public String getName() {
      return name;
   }

   public String getIdNum() {
      return idNum;
   }

   public void setAge( int newAge) {
      age = newAge;
   }

   public void setName(String newName) {
      name = newName;
   }

   public void setIdNum( String newId) {
      idNum = newId;
   }
}

The public setXXX() and getXXX() methods are the access points of the instance variables of the EncapTest class. Normally, these methods are referred as getters and setters. Therefore, any class that wants to access the variables should access them through these getters and setters.

The variables of the EncapTest class can be accessed using the following program −

/* File name : RunEncap.java */
public class RunEncap {

   public static void main(String args[]) {
      EncapTest encap = new EncapTest();
      encap.setName("James");
      encap.setAge(20);
      encap.setIdNum("12343ms");

      System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());
   }
}

This will produce the following result −

Output

Name : James Age : 20

Benefits of Encapsulation


Java

  1. Understanding Java’s final Keyword: Variables, Methods, and Classes
  2. Mastering Java Anonymous Inner Classes: Definition, Syntax, and Practical Examples
  3. Mastering Java’s ObjectInputStream: A Comprehensive Guide
  4. Mastering Java ObjectOutputStream: Serialization, Methods, and Practical Examples
  5. Mastering Java’s PrintStream Class: Print, Println, and Printf Explained
  6. Mastering Java Reader Class: Subclasses, Methods, and Practical Example
  7. Mastering Java Generics – Building Reusable, Type‑Safe Code
  8. Mastering Java File Operations with java.io – Creation, Reading, Writing & Deletion
  9. Java Encapsulation Explained: Secure Data Hiding & Control
  10. Master C# Encapsulation: Safeguarding Code and Boosting Design