How to encapsulate classes in Java?
In Java, access modifiers (public, private, protected) can be used to encapsulate classes.
Encapsulation is a vital concept in object-oriented programming, where it involves bundling data and methods within a class and controlling access to them through access modifiers.
The following are the general steps for encapsulation:
- Restrict direct access to a class’s properties by using the private access modifier.
- Provide public getter and setter methods to access and modify property values.
- Getter methods are used to retrieve the value of a property, typically starting with “get” followed by the name of the property, for example: getAge().
- The setter method is used to set the value of a property, usually starting with “set” followed by the name of the property, for example: setAge(int age).
Here is an example:
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age >= 0) {
this.age = age;
} else {
System.out.println("年龄不能为负数");
}
}
}
In the example above, the Person class has two private attributes, name and age. Use public getter and setter methods to access and modify the values of these attributes. Note that additional logic, such as validation of property values, can be added in the setter method.
Using encapsulation can hide the internal details of a class, making the code more secure and maintainable. Additionally, encapsulation also provides a mechanism to control access to the properties of a class, such as setting read-only or write-only properties.