Encapsulation
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from
users. To achieve this, you must:
• You learned from the previous chapter that private variables can only be accessed
within the same class (an outside class has no access to it). However, it is possible to
access them if we provide public get and set methods.
• The get method returns the variable value, and the set method sets the value.
• Syntax for both is that they start with either get or set, followed by the name of the
variable, with the first letter in upper case.
Example:
import java.util.*;
public class Encapsulation {
private String name = "Subhankar";
private String mob = "7554565514";
void defData() {
System.out.println("The name is: " + name);
System.out.println("The number is: " + mob);
}
String getAccess() {
return this.mob;
}
void setAccess(String number) {
this.mob = number;
}
}
class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String num;
Encapsulation en = new Encapsulation();
en.defData();
do {
System.out.print("Enter number for update: ");
num = sc.next();
if (num.length() == 10) {
en.setAccess(num);
break;
} else
System.out.println("Please enter correctly !\n");
} while (true);
en.defData();
}
}
Output:
Why Encapsulation?