variables within a class private | SoloLearn: Learn to code for FREE!

0

variables within a class private

why its not the rule?

12/19/2019 1:25:05 PM

Lenyuk Michal

2 Answers

New Answer

+2

You can’t force a programmer to make a variable private. But to achieve the encapsulation in Java you must have to create varibles with private keyword. Encapsulation is a process of wrapping the data (variables/attributes) and code acting on the data (methods/behavior) into a single unit. It is a mechanism that binds the variables and methods together. If you are creating class, it means you are doing encapsulation. We can create a fully encapsulated class in Java by making all the data members of the class private. In encapsulation, the variables of a class are not accessible from outside the class. because they are hidden in other classes. These variables can access only by the methods in which declared in the same class. We can Therefore, it is also known as data hiding. For more detail with examples you can read it https://javagoal.com/encapsulation-in-java/

+1

It is the rule. You must have heard about encapsulation, so exposing every variable of the class is not recommended because you do not want every user to alter the value of a program that you created. Edit: Need not be private at all times but it is a good practice.