Encapsulation in java and
programming example
Q.1 what is encapsulation?
Ø Encapsulation in java is a mechanism of wrapping the data (variables ) and code acting on the data (method)
together as a single unit.
Q.2 how to achieve encapsulation?
Ø Decelear the
variables of a class as private.
Ø Provide public
setter and getter method to modify
and view the values of the variable
Ø In encapsulation the variables of a class will be hidden from other classes and can be accessed only through the method of their current also this concept is known as data hiding.
Example:-
class Example
{
privet int id;
public void set Example_id(int id)
{
id= id; }
public int get Example_id()
return id;
}
}
Q.3 write a program to encapsulation ?
class Employee {
privet int
empid;
public void set Empid(int empi)
{
Empid =
empi ;
}
public int
getEmpid() {
return empid;
}
}
class Company
{
public void main (String args[])
{
Employee em= new Employee ();
em.setEmpid(6798);
System.out.println(em.getEmpid());
}
}
0 Comments