Java Tutorials
Java Methods
Java Classes
Java File Handling
Encapsulation definition, to ensure that "sensitive" data is hidden from users. To do this, you must:
private
private
variableYou learned in the preceding chapter that the private
variance can only be achieved in the same class (the external class cannot access it). However, we can only access them if we provide community get and set methods.
The get
method returns the variable value, and the set
method sets the value.
The syntax for both of you is the one that starts with get
or set
, followed by the word variable, with the first capital letter:
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
The get
method returns the value of the variable name
.
The set
method takes a parameter (newName
) and provides a variable name
. this
keyword is used to refer to the current object.
However, since the name
is declared private
, we cannot access it without this category:
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.name = "John"; // error
System.out.println(myObj.name); // error
}
}
Once the variable is declared public
, we can expect the following output:
John
However, as we try to access a different public, we find 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 use the getName()
and setName()
methods to access and update variables:
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName());
}
}
// Outputs "John"
read-only
(if you only use the get
method), or write-only
(if you only use default method)