Encapsulation

Encapsulation

  • Encapsulation is one of the oops concept, which provides security to our java code.
  • Binding (or wrapping) code and data together into a single unit is known as encapsulation.
  • A java class is the example of encapsulation.
  • In java method is a perfect example of encapsulation.
  • Java bean is the fully encapsulated class because all the data members are private here.
  • Encapsulation used to provide security.

Java Bean class Example for Encapsulation

[pastacode lang=”java” manual=”%0Aclass%20Employee%0A%7B%0A%09private%20int%20id%3B%0A%09private%20String%20name%3B%0A%09private%20double%20salary%3B%0A%09%09%0A%09public%20Employee(int%20id%2CString%20name%2Cdouble%20salary)%0A%09%7B%09%0A%09%09this.id%3Did%3B%0A%09%09this.name%3Dname%3B%0A%09%09this.salary%3Dsalary%3B%0A%09%7D%0A%0A%09%2F%2Fpublic%20getter%20and%20setter%20method%09%0A%09public%20int%20getid()%0A%09%7B%0A%09%09return%20id%3B%0A%09%7D%0A%09public%20void%20setid(int%20id)%0A%09%7B%0A%09%09this.id%3Did%3B%0A%09%7D%0A%0A%09public%20String%20getname()%0A%09%7B%0A%09%09return%20%22bhavesh%22%3B%0A%09%7D%09%0A%09public%20void%20setname(String%20name)%0A%09%7B%0A%09%09this.name%3Dname%3B%0A%09%7D%0A%09%0A%09%0A%09public%20double%20getsalary()%0A%09%7B%0A%09%09return%20salary%20%3B%0A%09%7D%0A%09public%20void%20setsalary(double%20salary)%0A%09%7B%0A%09%09this.salary%3Dsalary%3B%0A%09%7D%0A%7D%0A%0Apublic%20class%20JavaBeanclass%0A%7B%0A%09public%20static%20void%20main(String%5B%5D%20args)%20%7B%0A%09%09%0A%09%09System.out.println(%22***************************%22)%3B%0A%09%09%09%09%0A%09%09Employee%20emp%3Dnew%20Employee(1%2C%20%22bhavesh%22%2C%2023.9)%3B%0A%09%09%0A%09%09System.out.println(%22Employee%20id%3A%20%22%2Bemp.getid())%3B%0A%09%09System.out.println(%22Employee%20name%3A%20%22%2Bemp.getname())%3B%0A%09%09System.out.println(%22Employee%20salary%3A%20%22%2Bemp.getsalary())%3B%0A%09%09System.out.println(%22***************************%22)%3B%0A%09%09%0A%09%09emp.setsalary(2344.23)%3B%0A%09%09%0A%09%09System.out.println(%22Employee%20Salry%3A%20%22%2Bemp.getsalary())%3B%0A%09%7D%0A%09%0A%7D%0A” message=”” highlight=”” provider=”manual”/]

output:
***************************
Employee id: 1
Employee name: bhavesh
Employee salary: 23.9
***************************
Employee Salry: 2344.23




		
		
	

Leave a Reply