Tuesday, 19 December 2017

Chapter 4: Encapsulation

Chapter 4: Encapsulation

What is encapsulation ?

Encapsulation is a process of wrapping code and data together into a single unit.

We can create a fully encapsulated class in java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.

Encapsulation provides control over data.

Example of Encapsulation.

//save this program as customer.java  


package com.testpackage;  
public class customer{  
private String name;  
public String getName(){  
return name;  
}  
public void setName(String name){  
this.name=name  
}  
}  

//save this program as test.java 
 
package com. testpackage;  
class test{  
public static void main(String[] args){  
customer c=new customer();  
c.setName("Raj");  
System.out.println(c.getName());  
}  
}