在Java中,實現有效封裝的關鍵是使用訪問修飾符(如private、protected和public)來控制類成員的訪問權限。以下是一些建議:
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 && age <= 150) {
this.age = age;
} else {
throw new IllegalArgumentException("Invalid age");
}
}
public class OuterClass {
private String secret = "This is a secret";
public class InnerClass {
public void printSecret() {
System.out.println(secret);
}
}
}
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
遵循以上建議,可以幫助您在Java中實現有效的封裝,提高代碼的可維護性、可擴展性和安全性。