Encapsulation in java

Encapsulation is a process of wrapping of data and methods in a single unit is called encapsulation. Encapsulation is achieved in java language by class concept.

Combining of state and behavior in a single container is known as encapsulation. In java language encapsulation can be achieve using class keyword, state represents declaration of variables on attributes and behavior represents operations in terms of method.

Advantage of Encapsulation in java

By providing only setter or getter method, you can make the class read-only or write-only.

It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.

Benefits of encapsulation

  • Provides abstraction between an object and its clients.
  • Protects an object from unwanted access by clients.
  • Example: A bank application forbids (restrict) a client to change an Account’s balance.

Let’s see the Example of Encapsulation in java

Example

class Employee

{  

private String name;  

   

public String getName()

{  

return name;  

}  

public void setName(String name){  

this.name=name;

}  

}  

 

class Demo

{  

public static void main(String[] args)

{  

Employee e=new Employee();  

e.setName("Harry");  

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

}  

}  

Output

Harry

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s