Encapsulation means binding the states (attribute) and behaviours
(methods) in a single unit. Class is the best example of Encapsulation
in java. In java, Encapsulation is achieved by making fields as
private and providing access to them via public methods. These methods
are known as getter and setter methods.
The objective of encapsulations is to show what is necessary to the
user and hiding the implementation mechanism.
How to achieve Encapsulation:
- Make fields in class as private.
- Create public getter and setter methods to access the fields.
By declaring the fields as private, we can restrict access from
outside of that class. We are creating the getter and setter methods
to access the fields and allowing read or modify using those methods
only.
Example:
// Encapsulation example
public class Person {
private String name;
private String age;
public int getName() {
return name;
}
public String getAge() {
return age;
}
public void setName( int name) {
name = name;
}
public void setAge(String age) {
age = age;
}
}
In the above Person class, there are two private variables name and
age and getter and setter methods to access those variables.
Person person = new Person();
person.name = "John"; //Error
In the above code, you can see we have created an object
for Person class and trying to modify the name of the person directly. In
this case, we will get an error because the variable name is private.
Person person = new Person();
person.setName = "John"; //Correct
System.out.pritnln("Name is:
"+person.getName());
The above code is the right example for creating (set) the name and
reading (get) of a Person object.
public void setAge(int age) throws Exception {
if(age < 18 || age > 80)
throw new Exception("Enter valid Age");
else
this.age = age;
}
In the above code setAge method, there is a condition to validate the
user entered age. If any user is trying to enter age as 90 program
throws an exception. So, you understand that Encapsulation is the
process of hiding the implementation to the outside world and showing
what is necessary.
0 Comments