Encapsulation In Java With Real Time Example

Encapsulation in java with real time example for beginners to understand encapsulation in java. In Java, encapsulation is a strategy for enclosing data and the code that acts on the data as a single unit. 

Encapsulation means that a class’s variables are concealed from other classes and can only be accessible through the methods of their current class. 

Encapsulation is the act of grouping together data and functions into a single unit known as a class. The data is not accessible directly in Encapsulation; rather, it is retrieved via the functions included within the class.

Advantages of Encapsulation in Java

It gives you control over the data. If you want to set the value of id to be more than 100 alone, you may do it within the setter method. 

You may create logic to prevent negative integers from being stored in the setter methods. 

It is a method of achieving data concealing in Java since other classes will be unable to access the data through private data members.

The encapsulate class is simple to put to the test. As a result, it is preferable for unit testing. 

The ability to produce getters and setters is provided by common IDEs. As a result, creating an enclosed class in Java is simple and quick.

Class Definition in Java

In the context of Java, a class is a template that is used to construct objects and specify object data types and functions. 

Classes are subcategories, and objects are things inside those subcategories. The real attributes/values and methods that the object may utilise are considered core properties.

Private Class in Java Program

Private is a Java keyword that indicates that a member’s access is restricted. That is, the member is exclusively visible within the class and not from any other class or subclass. Private members’ visibility extends to nested classes.

Public Class in Java

The Java keyword public declares a member’s access to be public. All other classes can see public members. This indicates that a public field or function can be accessed by any other class. 

Furthermore, unless a public field is designated as final, other classes can edit it. These are major methods which are required to execute encapsulation in java with real time example

class Encapsulate {
private String Name;
private int Roll;
private int Age;
public int getAge() { return Age; }
public String getName() { return Name; }
public int getRoll() { return Roll; }
public void setAge(int newAge) { Age = newAge; }
public void setName(String newName)
{
Name = newName;
}
public void setRoll(int newRoll) { Roll = newRoll; }
}
public class Main 
{
public static void main(String[] args)
{
Encapsulate obj = new Encapsulate();
obj.setName("Jammy");
obj.setAge(34);
obj.setRoll(51);
System.out.println("Name: " + obj.getName());
System.out.println("Age: " + obj.getAge());
System.out.println("Roll: " + obj.getRoll());
}
}

Output:

Name: Jammy
Age: 34
Roll: 51