java - 这个私有(private)变量如何访问?

标签 java private

当我编写以下代码时,编译器如何不报错?

public class MyClass 
{
    private int count;

    public MyClass(int x){
        this.count=x;
    }

    public void testPrivate(MyClass o){
        System.out.println(o.count);
    }   
}

即使它是编写 testPrivate 的同一类的实例,它不应该在 System.out.println(o.count) 处给出编译错误?毕竟,我是在尝试直接访问私有(private)变量。
代码甚至运行良好。

最佳答案

可以从声明它的类中的任何方法访问私有(private)成员,无论该方法是访问其自己的 (this) 实例的私有(private)成员还是某个其他实例的私有(private)成员。

这在 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.

Java 的这一特性允许您编写接受类实例作为参数的方法(例如 - clone(Object other)compareTo(Object other)) 不依赖于对所有需要访问的私有(private)属性具有非私有(private) getter 的类。

关于java - 这个私有(private)变量如何访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27482579/

相关文章:

java - 如何通过反射访问私有(private)方法和私有(private)数据成员?

java - 如何在 Windows 上使用 Java 清除浏览器中的私有(private)数据(临时文件、缓存、cookie)

java - 有关 Cloud Endpoints 返回类型的更多信息

java - 无法在 Spring MVC Controller 测试中模拟服务类

Java 类无法编译

c# - C# 中的类修饰符问题与 "private"类

javascript - 并非 Meteor 项目私有(private)文件夹中的所有 Assets 都会自动部署到 ".meteor\local\build\programs\server\assets\app"

module - 如何在 Rust 中相互隐藏兄弟模块?

winapi - 如何在 Windows 上检测已安装的 Sun/Oracle JRE?

java - 将由特定单词分隔的句子分组