Java Language Encapsulation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any Java Language Question?