Automation Using Selenium Webdriver
Showing posts with label Encapsulation in Java. Show all posts
Showing posts with label Encapsulation in Java. Show all posts

Wednesday, 28 September 2016

Encapsulation

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

The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class.

Real life example of Encapsulation

The common example of encapsulation is capsule. In capsule all medicine are encapsulated in side capsule.
real life example of encapsulation

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