Encapsulation ensures that “sensitive” data is concealed from users. To accomplish this, you need to:
As learned from the previous chapter, private variables are only accessible within the same class, denying access from outside classes. Nonetheless, accessibility can be facilitated by providing public get and set methods.
The get method retrieves the variable value, while the set method assigns a value to it.
Both methods follow a syntax where they begin with either get or set, followed by the variable name, with the initial letter capitalized:
public
}
|
The get method retrieves the value of the variable name.
The set method accepts a parameter (newName) and assigns it to the name variable. The “this” keyword is employed to reference the current object.
However, since the name variable is declared as private, access to it from outside this class is prohibited.
public
}
|
Had the variable been declared as public, the expected output would be as follows:
John
|
Attempting to access a private variable results in an error.
MyClass.java:4: error: name has private access in Person
myObj.name = "John";
^
MyClass.java:5: error: name has private access in Person
System.out.println(myObj.name);
^
2 errors
|
Instead, we utilize the getName() and setName() methods to retrieve and modify the variable.
|