Encapsulation in Java

Encapsulation in Java( features of oop ) is the wrapping of data and function into a single entity. It describes the idea of rolling data and methods that task on that data within one crew. It acts as a protective shield to prevent the data accessed by the outside.The encapsulate meaning in hindi is to enclose.

Real world example of encapsulation

class EncapsulationDemo
{
private int s;
private String empName;
private int empAge;
public int getEmpS()
{ 
return s;
}
public String gerEmpName()
{
return empName;
}
public int getEmpAge()
{
return empAge;
}
public void setEmpAge(int newValue)
{
empAge = newValue;
}
public void setEmpName(String newValue)
{
empName = newValue;
}
public void setEmps(int newValue)
{
s= newValue;
}
}
public class EncapsTest
{
Public static void main(String args[])
{
EncapsulationDemo obj1 = new EncapsulationDemo1();
obj.setEmpName("Shiffana");
obj.setEmpAge(24);
obj.setEmpS(13487);
System.out.println("Employee Name: " + obj.getEmpName());
System.out.println("Employee S: " + obj.getEmpS());
System.out.println("Employee Age: " + obj.getEmpAge());
}
}

Output:

Employee Name: Shiffana
Employee S: 13487
Employee Age: 24

Advantages of Encapsulation

Following are the advantages of encapsulation.

  • Data Hiding
  • Increased Flexibility
  • Reusability
  • Testing code is easy

Data Hiding

The concept is also often used to hide the internal representation, or state, of an object from the outside this is called Information or Data Hiding.

Real world example of encapsulation

class Person
{
private int age;
public int getAge()
{
return age;
}
public void setAge(int age)
{
p.age =age;
}
}
class main
{
public static void main(String[] args)
{
Person p1 = new Person();
p.setAge(24);
System.out.println(“My age is” + p1.getAge());
}
}

Output:

My age is 24

So that the personal field is the age it cannot be accessed by any because it is non-public. The getter (getAge()) and setter (setAge()) are public in order to attainable age. Making the age private allowed us to restrict unauthorized access from external the class so that it is called us data hiding.

Increased Flexibility

GET and SET

  • Class attributes can be built read-only (if you can only utilize the GET method)
  • Class attributes can be built write-only (if you can only utilize the SET method)

Real world example of encapsulation

public class person
{
private string age;
public string getAge()
{
return age;
}
public void setAge(String newName)
{
p.name = newAge;
}
}
  • GET method sends back the value of the variable name.
  • SET method takes a parameter and that it is a named variable. The same variable is declared as private.

Reusability

Encapsulation also makes it better than re-usability and easy to change with new necessary.

Testing code is easy

Encapsulated code is easy to test for crew testing.

Leave a Reply