Encapsulation principle in Java

The principle of encapsulation in Java makes sense: an object does not allow external objects to directly access the properties of that object, must via the methods that the object allows.

The example below the Student object has two properties named name and age, which define the access modifier of these two properties as private, so that no object outside of the Student object can be accessed. External objects can only access them through Getter, Setter methods.

Why need to use the encapsulation principle

The private property of an object is used to hide information about that object. If we do not use the encapsulation principle, the state and behavior of the object will be easily accessed and replaced by other objects if it is not properly encapsulated.

In the following example, the object’s age and name attributes are defined with the access modifier public:

therefore, these attributes can be easily accessed and changed from other objects.

Use the encapsulation principle

We use the encapsulation principle to manage how other objects get access to the properties of our object.

In the following example, the age attribute of a Student object can only be retrieved from another object, not change its value, and the name attribute can be changed its value by another object.

The purpose of the encapsulation principle is to hide the object’s information. By using methods, we can prevent private properties from being assigned values from other objects.

A well-encapsulated object is an object whose properties are defined with the access modifier private and which only allows other objects to access their properties through methods.

Add Comment