Java Reference
In-Depth Information
Encapsulation
In object oriented programming languages you can hide data from other classes. You can do
this using “get” and “set” methods. You can declare your variables as private so that they are
completely invisible from outside. Later you can use get and set methods to initialize and
provide values to these variables.
public class Encapsulate{
private String name;
private int age;
public int getAge () {
return age;
}
public String getName () {
return name;
}
public void setAge ( integer newAge) {
age = newAge;
}
public void setName(String newName){
name = newName;
}
}
In the example above we have created 2 private variables age and name in the class Encap-
sulate. These variables can not be accessed from any other class. Now if we want to access
them then it can be only through the methods getname() and getAge(). If we want to set val-
ues to them it is possible only through the methods setName() and setAge(). Even though it
looks like we have to write unnecessary code but it has advantages. In procedural program-
ming languages, we could access a variable only if they are publicly accessible. Publicly de-
claring variables leads to any code changing their values and managing your code extremely
difficult. Imagine you have a publicly declared variable and it is accessed by some 10 pieces
of code located at many other places. Which of them accessed and changed values of the
variables will be a nightmare to find. Debugging will be extremely difficult.
However in our case this nightmare will not happen.
Search WWH ::




Custom Search