Encapsulation In Java
We’ll be talking about Java encapsulation today in the hopes that it will help us achieve our learning goals.
Encapsulation, in Java, means hiding sensitive data from users, which is what is meant by Java encapsulation. For Example:
Tesla designs and manufactures electrical vehicles (electric cars and trucks) that are based on AI modules. In spite of providing the buyer with all the luxuries, the company keeps all its key ideas and codes to itself.
This inhibits ordinary users from having access to them or being able to breach or modify them in any way. This is where encapsulation comes into play.
You must follow these steps to achieve this:
- The variables/attributes of a class should be declared private.
- You can access and update the value of a private variable by providing public get and set methods.
Get and Set
The previous chapter taught you that private variables are only accessible within the same class (they cannot be accessed by outside classes). Providing public get and set methods, however, allows access to them.
Values can be returned by the get method, and values can be set by the set method.
They both begin with either get or set, followed by the variable’s name with an uppercase first letter:
The get method returns the value of the variable topic.
The set method takes a parameter (new_Topic) and assigns it to the topic variable.
This keyword is used to refer to the current object.
However, as the topic variable is declared private, we cannot access it from outside this class.
The following output would be expected if the variable was made public.
Getter and Setter
Attempting to access a private variable, however, results in an error:
MyClass.java:4: error: topic has private access in Main my_Object.topic = "Getter and Setter"; ^ MyClass.java:5: error: topic has private access in Main System.out.println(my_Object.topic); ^ 2 errors
As an alternative, we can access and update the variable by using geTopic() and setTopic():
Similarly, the private ample age can be accessed by using getAge() and setAge() methods:
- Methods and attributes of classes can be better controlled.
- When using only the get or set methods, attributes can be set to be read-only or write-only.
- Code is flexible: the programmer can modify one part without affecting other parts.
- Data security is improved.