How is this private variable accessible?

A private member is accessible from any method within the class in which it is declared, regardless of whether that method accesses its own (this) instance’s private member or some other instance’s private member.

This is stated in JLS 6.6.1:

…Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (ยง7.6) that encloses the declaration of the member or constructor.

This feature of Java allows you to write methods that accept an instance of the class as an argument (for example – clone(Object other), compareTo(Object other)) without relying on the class having non private getters for all the private properties that need to be accessed.

Leave a Comment