Java OOPs- Encapsulation

We can create a fully encapsulated class in java by making all the data members i.e attributes of the class private and provide getters and setters to modify or view the same.

public class Student {

private int studentId;

private String name;

private String gender;

private int age;

private String department;

public int getStudentId() {
return studentId;
}

public void setStudentId(int studentId) {
this.studentId = studentId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}

}

By declaring the member variables as private , a class can have total control over what is being stored in its fields. Other classes can only access the data members of above class through their getters and setters, the former dont have the right to manipulate the data members.

Consider, a public field in a class which can be directly accessed or modified by other classes. Now suppose later on, you want to add any extra logic while getting and setting the variable. This will impact all the other classes that uses the above declared class. So any changes to this public field will require change to each class that refers it. On the contrary, with an accessor or setter method, one can easily add some logic like cache some data(There are times when you dont want to hit the database again and again to get some data and you just add @cache to the getter method so that the data is cached and your hits to database are saved) manipulate the value passed and then return or set the member value without impacting other classes using the members.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s