Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class, therefore it is also known as data hiding.
Benefits of Encapsulation:
- The fields of a class can be made read-only or write-only.
- A class can have total control over what is stored in its fields.
- The users of a class do not know how the class stores its data. A class can change the data type of a field and users of the class do not need to change any of their code.
To achieve encapsulation in Java
- Declare the variables of a class as private.
- Provide public setter and getter methods to modify and view the variables values.
Programe on Encapsulation to find the sum of 2nos
class sum
{
private int a,b,c;
public void setValues(int x,int y)
{
a=x;
b=y;
}
public int getValues()
{
return (a+b);
}
}
class sample
{
public static void main(String args[])
{
sum x=new sum();
x.setValues(5,6);
System.out.println(“Sum of 2nos “+(x.getValues());
}
}
Programe on employ information using encapsulation
class emp
{
private int eno,sal;
private String ename;
public void setEno(int x)
{
eno=x;
}
public void setEname(String x)
{
ename=x;
}
public void setSal(int x)
{
sal=x;
}
public int getEno()
{
return eno;
}
public String getEname()
{
return ename;
}
public int getSal()
{
return sal;
}
}
Class sample
{
Public static void main(String args[])
{
Emp x=new emp();
x.setEno(100);
x.setEname(“Prasad”);
s.setSal(3200);
System.out.println(x.getEno()+” “+x.getEname()+” “+x.getSal());
}
}
For
More Explanation
&
Online Classes
More Explanation
&
Online Classes
Contact Us:
+919885348743
+919885348743