LoginSignup
3
1

More than 5 years have passed since last update.

【Java】privateによるフィールドのアクセス制限はオブジェクト単位ではなくクラス単位

Last updated at Posted at 2017-07-30

Javaの仕様の話。

Javaのドキュメントには、下記のように書いてある。

The private modifier specifies that the member can only be accessed in its own class.

つまり、同じクラスに属する異なるオブジェクトからはアクセスできる。(勘違いしがちな部分)

例1

引数に同じクラスのオブジェクトを受け取ることで、そのprivateフィールドを直接操作することができる。(getter, setterは不要)

public class Foo {
    private int num;

    public void setNumToAnotherFoo(Foo foo, int num) {
        foo.num = num;
    }
}

例2

フィールドに同じクラスのオブジェクトをもつとき、そのprivateフィールドは直接操作することができる。


public class Bar {
    private Bar barField;
    private int num;

    public void setBarFieldNum(int num) {
        barField.num = num;
    }
}

参考文献

  • ケン・アーノルド、ジェームズ・ゴスリン、デビッド・ホームズ(2014)『プログラミング言語Java 第4版』柴田芳樹訳、東京電機大学出版局
    • 2.6.6 アクセス制御のためのメソッド使用
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1