Monday, April 11, 2011

Encapsulation හඳුනා ගනිමු.....!

උදාහරණයක් සලකමු.

class woman{
private int age;

public int getAge(){
return age;
}

public void setAge(int x){
age=x;
}
}

මෙහි woman class එකේ ඇති age නම් variable එකට private access modifier එක යොදා ඇත.
එමනිසා එහි අගය ලබාගැනීම හෝ වෙනස් කිරීම වෙනත් class වල සිට කල නොහැක.
මෙය encapsulation ලෙස හැඳින්වෙයි.

Class එකක ඇති සියළු variables(properties) private විට එය encapsulated class එකකි.

ex) class A{
private int x;
} //encapsulated class

ex) class B{
private int p;
int q;
} // not encapsulated.

getter සහ setter methods ඇතිවිට එය tightly encapsulated class එකක් ලෙස හැඳින්වෙයි.


ex)class A{
private int x;
}

class B extends A{
int y;
}

1) variable x පමනක් private නම් class A encapsulated.නමුත් class B encapsulated නොවේ.

2) x,y දෙකම private නම්,A,B classes දෙකම encapsulated වේ.

3)y පමණක් private නම්, classes දෙකම encapsulated නොවේ.


Encapsulation හි භාවිත

1.data hiding
2.data immutability
3.validation

1.data hiding

variable age හි අගය වෙනත් class එකක සිට ලබාගත නොහැක.

public class woman{
private int age;

public void setAge(int x){
age=x;
}
}

2.data immutability

variable age හි අගය වෙනත් class එකක සිට වෙනස් කල නොහැක.

class woman{
private int age;

public int getAge(){
return age;
}
}

නමුත් class එක තුල සිට මෙහි අගය වෙනස් කල හැකිය.

method 1) private void doChange(){
age=20;}

method 2) woman(int x){
this.age=x;}

නමුත් variable එක final කලහොත් කොහේ සිටවත් වෙනස් කල නොහැක.

3) Validation

public class woman{
private int age;

public void setAge(int x){
if(x>25){
age=x;
}else{
throws IllegalArgumentException;
}
}