Encapsulation

suggest change

Versions

[{“Name”:“Java SE 1.0”,“GroupName”:null},{“Name”:“Java SE 1.1”,“GroupName”:null},{“Name”:“Java SE 1.2”,“GroupName”:null},{“Name”:“Java SE 1.3”,“GroupName”:null},{“Name”:“Java SE 1.4”,“GroupName”:null},{“Name”:“Java SE 5”,“GroupName”:null},{“Name”:“Java SE 6”,“GroupName”:null},{“Name”:“Java SE 7”,“GroupName”:null},{“Name”:“Java SE 8”,“GroupName”:null},{“Name”:“Java SE 9 (Early Access)”,“GroupName”:null}]

Introduction

Imagine you had a class with some pretty important variables and they were set (by other programmers from their code) to unacceptable values.Their code brought errors in your code. As a solution, In OOP, you allow the state of an object (stored in its variables) to be modified only through methods. Hiding the state of an object and providing all interaction through an objects methods is known as Data Encapsulation.

Remarks

It is much easier to start with marking a variable private and expose it if necessary than to hide an already public variable.

There is one exception where encapsulation may not be beneficial: “dumb” data structures (classes whose sole purpose is to hold variables).

public class DumbData {
    public String name;
    public int timeStamp;
    public int value;
}

In this case, the interface of the class is the data that it holds.

Note that variables marked final can be marked public without violating encapsulation because they can’t be changed after being set.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents