Encapsulation in Java


Encapsulation is grouping of the properties and methods within a class.

Providing access to an object only through its messages,while keeping the details private is called information hiding.An equivalent term to information hiding is encapsulation.Encapsulation is a process that allows selective hiding of properties and methods in a class.The advantage of encapsulation is that a class can have many properties and methods but only some of these are exposed to the user.

In example of an organization there are many methods and properties of the organization that are classified as private.When a company B deals with company A,it does not interfere with the way in which Company A functions.Any information that Company B needs has to be strictly routed through proper channels such as,the public relations offer or administrative manager of Company A.

When code is properly encapsulated two objectives are achieved:

1. we build an impenetrable wall to protect the code from accidental corruption due to the silly little errors that we are all prone to make.

2. we also isolate errors to small sections of code to make them easier to find and fix.

 

 Example of  Encapsulation in Java:

import java.io.*;
class EncapsDemo
{
private int sn;
private String empName;
private int empAge;

//Getter and Setter methods

public int getEmpSN()
{
return sn;
}

public String getEmpName()
{
return empName;
}

public int getEmpAge()
{
return empAge;
}

public void setEmpAge(int newValue)
{
empAge = newValue;
}

public void setEmpName(String newValue)
{
empName = newValue;
}

public void setEmpSN(int newValue)
{
sn = newValue;
}
}

public class ee
{
public static void main(String args[])
{
EncapsDemo obj = new EncapsDemo();
obj.setEmpName(“veneeta”);
obj.setEmpAge(22);
obj.setEmpSN(102030);
System.out.println(“Employee Name: ” + obj.getEmpName());
System.out.println(“Employee SSN: ” + obj.getEmpSN());
System.out.println(“Employee Age: ” + obj.getEmpAge());
}
}

OUTPUT:

 

 

 

 

 

In above example all the three data members (or data fields) are private which cannot be accessed directly. These fields can be accessed via public methods only. Fields empName, sn and empAge are made hidden data fields using encapsulation technique of OOPs.

 

 

Comments are closed.