Font Awesome Icons

Tutorial

Encapsulation in Java

  • It is the mechanism that binds together code and the data it manipulates in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared.

  • As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.

  • Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables. (Getters and setters method to set and get the values of the fields.)

 

 

class Employee

{    

private int uid;    

private String empName;    

private int empAge;

public int getEmpuid()

{        

return uid;    

}

            public String getEmpName()

{        

return empName;    

}

            public int getEmpAge()

{        

return empAge;     

}

            public void setEmpAge(int  empAge)

{        

this.empAge =  empAge;    

}

            public void setEmpName(String empName)

{        

this.empName = empName

}

            public void setEmpuid(int uid)

{        

this.uid = uid;    

}

}

public class Encapsulate

{    

public static void main(String args[])

{     

Employee obj = new Employee();         

obj.setEmpName(“Gosling”);         

obj.setEmpAge(67);         

obj.setEmpuid(55773021);         

System.out.println(“Employee Name: ” + obj.getEmpName());          System.out.println(“Employee UID: ” + obj.getEmpuid());   

    System.out.println(“Employee Age: ” + obj.getEmpAge());    

}