这个私有变量怎么可以访问? [英] How is this private variable accessible?

查看:122
本文介绍了这个私有变量怎么可以访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写以下代码时编译器如何不抱怨?

How is the compiler not complaining when I write the following code?

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)中给出编译错误?毕竟,我试图直接访问私有变量。

代码甚至运行正常。

Even though it is an instance of the same class in which testPrivate is written, shouldn't it give a compilation error at System.out.println(o.count)? After all, I am trying to access a private variable directly.
The code even runs fine.

推荐答案

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

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.

这在 JLS 6.6.1


...否则,如果成员或构造函数被声明为private,则当且仅当它发生在包含成员或构造函数声明的顶级类(第7.6节)的主体内时才允许访问。

...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))而不依赖于具有非私有getter的类,用于所有需要的私有属性要访问。

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.

这篇关于这个私有变量怎么可以访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆