如果您在 Java 中有私有静态嵌套类,是否仍然建议使用 getter 和 setter 而不是直接字段访问?
一个例子。直接字段访问:
public class Application {
private List<MyInnerClass> myInnerClassList;
// ...
public void foo() {
MyInnerClass inner = new MyInnerClass();
inner.bar = 50;
myInnerClassList.add(inner);
}
private static class MyInnerClass {
private int bar;
}
}
与封装:
public class Application {
private List<MyInnerClass> myInnerClassList;
// ...
public void foo() {
MyInnerClass inner = new MyInnerClass();
inner.setBar(50);
myInnerClassList.add(inner);
}
private static class MyInnerClass {
private int bar;
public int getBar() {
return bar;
}
public void setBar(int bar) {
this.bar = bar;
}
}
}