[Java] Private field access restrictions are not per object but per class

Talk about Java specifications.

The Java documentation says:

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

https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

That is, it can be accessed by different objects that belong to the same class. (The part that is easy to misunderstand)

Example 1

By receiving an object of the same class as an argument, you can directly manipulate the private field. (No getter or setter required)

public class Foo {
    private int num;

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

Example 2

When a field has objects of the same class, the private field can be manipulated directly.


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

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

References

Recommended Posts

[Java] Private field access restrictions are not per object but per class
[Java] Object class
Java class type field
[Java] Wrapper that executes private method of object from outside class
Why are class variables needed? [Java]
java (use class type for field)