private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void printAge() {
System.out.println("Age is: " + getAge());
}
public void setNewAge(int newAge) {
setAge(newAge);
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age >= 0 && age <= 120) {
this.age = age;
} else {
throw new IllegalArgumentException("Age must be between 0 and 120");
}
}
@Getter
和@Setter
注解即可。import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
private int age;
以上是一些使用property的get和set方法的技巧,可以根据具体需求灵活运用。