Java Encapsulation
Encapsulation is the practice of hiding fields inside a class and reaching them through methods. The class controls each change to its data.
Set a value, then get it back
The setter stores 25 in the private age field. The getter returns the stored value, and the print shows 25.
class Person {
private int age;
public int getAge() {
return age;
}
public void setAge(int newAge) {
if (newAge >= 0) {
age = newAge;
}
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setAge(25);
System.out.println(person.getAge());
}
}A bad value is refused
The first setter call stores 25. The second call passes -5, the setter stores nothing, and the getter still returns 25.
class Person {
private int age;
public int getAge() {
return age;
}
public void setAge(int newAge) {
if (newAge >= 0) {
age = newAge;
}
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setAge(25);
person.setAge(-5);
System.out.println(person.getAge());
}
}The starting value before any set
No setter call runs in this program. The getter returns the starting value of the field, which is 0.
class Person {
private int age;
public int getAge() {
return age;
}
public void setAge(int newAge) {
if (newAge >= 0) {
age = newAge;
}
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.getAge());
}
}Example
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public int getAge() {
return age;
}
public void setAge(int newAge) {
if (newAge >= 0) {
age = newAge;
}
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("Ada");
person.setAge(36);
person.setAge(-1);
System.out.println(person.getName());
System.out.println(person.getAge());
}
}Key points
- Encapsulation keeps fields private inside the class.
- A getter method returns the value of a field.
- A setter method stores a new value in a field.
- A setter can refuse a value that breaks the rules of the class.
- Code outside the class calls the getter and setter instead of the field.
In this example, the Person object receives a name and an age through its setters. The call with -1 tries to replace the age, and the setter refuses it. The prints show Ada and 36, the values the setters accepted.
Note
Private fields force access through methods, so the two ideas work as a pair.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why does a setter check a new value before it stores the value?