Java 访问修饰符最佳实践

Java Access Modifier Best Practice

这似乎是一个基本问题,但我想做对。

我有一个Class'AWorld'。在那个 class 中,我有一个绘制边框的方法,具体取决于用户设置的地图大小。

如果变量 'mapSize' 是私有的,但我想从同一个 class 中访问它的值,是直接引用它更合适,还是使用 getter方法。

下面的代码应该可以解释我想知道的内容。

package javaFX;

public class AWorld {
    //initialized later
    AWorld newWorld;

    private int mapSize = 20;

    public int getMapSize()
    {
        return mapSize;
    }

    public void someMethod()
    {
        int var = newWorld.mapSize; //Do I reference 'mapSize' using this...
    }
    // Or...

    public void someOtherMethod()
    {
        int var = newWorld.getMapSize(); //Or this?
    }
    public static void main(String[] args) {}

}

这两个都可以,因为您得到的是原始字段。如果 get 方法在返回数据之前执行另一个操作,例如对值执行数学运算,那么最好使用它而不是直接调用该字段。这特别意味着在 类.

上使用 proxy/decorator 模式时

下面是上面第二个语句的示例:

//base class to be decorated
abstract class Foo {
    private int x;
    protected Foo foo;
    public int getX() { return this.x; }
    public void setX(int x) { this.x = x; }
    public Foo getFoo() { return this.foo; }

    //method to prove the difference between using getter and simple value
    public final void printInternalX() {
        if (foo != null) {
            System.out.println(foo.x);
            System.out.println(foo.getX());
        }
    }
}

//specific class implementation to be decorated
class Bar extends Foo {
    @Override
    public int getX() {
        return super.getX() * 10;
    }
}

//decorator
class Baz extends Foo {
    public Baz(Foo foo) {
        this.foo = foo;
    }
}

public class Main {
    public static void main(String[] args) {
        Foo foo1 = new Bar();
        foo1.setX(10);
        Foo foo2 = new Bar(foo1);
        //here you see the difference
        foo2.printInternalX();
    }
}

输出:

10
100

你最好直接取消引用它。

private 修饰符的意义在于不向其他 classes 公开内部实现。这些其他 classes 将使用 getter 方法来获取私有 属性.

的值

在您自己的 class 中,使用 getter 没有任何意义。更糟糕的是,有人可能已经在 class 中覆盖了那个扩展你的 class 的方法,并且 getter 可能会执行一些你不期望的事情

恕我直言,如果您引用当前实例的字段,一般规则是直接使用 mapSizethis.mapSize 访问该字段。

如果您引用来自不同实例的值(无论是相同的 class 还是不同的 class,我会使用 getter 方法)。我相信这会导致更简单的重构。它还维护任何其他实例通过 getter 获取字段值的合同,这允许 getter.

中的附加功能