What is Encapsulation?
---------------------------------------
Encapsulation is wrapping code and data together into one single unit.
Encapsulation in java is performed using class. A class wraps code (method) and data(variables) together.
Advantages of Encapsulation in Java
----------------------------------------
Encapsulation in java has many advantages, which are mentioned below :
We can make read-only and write-only classes using encapsulation.
We can achieve data hiding.
We have control over data.
----------------------------------------
class Watch{
private int min_Hand;
private int hr_Hand;
private int sec_Hand;
Watch()
{ hr_Hand=10;
min_Hand=10;
sec_Hand=10;
}
Watch(int hr_Hand,int min_Hand,int sec_Hand)
{this.hr_Hand=hr_Hand;
this.min_Hand=min_Hand;
this.sec_Hand=sec_Hand;
}
//Getter
public int getMin_Hand()
{
return min_Hand;
}
public int getHr_Hand()
{
return hr_Hand;
}
public int getSec_Hand()
{
return sec_Hand;
}
//Setter
public void setHr_Hand(int hr_Hand)
{
this.hr_Hand=hr_Hand;
}
public void setMin_Hand(int min_Hand)
{
this.min_Hand=min_Hand;
}
public void setSec_Hand(int sec_Hand)
{
this.sec_Hand=sec_Hand;
}
void showTime()
{
System.out.println("Hr: "+hr_Hand+" Min: "+min_Hand+" Sec: "+sec_Hand);
}
}
class Test{
public static void main(String[] args) {
Watch w1=new Watch();
//w1.min_Hand=11; //cant accesss memmber
//directly
w1.showTime();
Watch w2=new Watch(5,30,45);
int hour=w2.getHr_Hand();
System.out.println(hour);
}
Thanks Sir! :)
ReplyDelete