简体   繁体   English

在Java类之外访问私有变量

[英]Accessing private variable outside its class in java

The following Java programs compiles successfully. 以下Java程序成功编译。 I am expecting an error in the statement y.className = "No class name."; 我期待语句y.className = "No class name."; since the private variable className are accessed outside its class. 因为私有变量className是在其类外部访问的。

class t { 

    public static void main(String[] r) {

        Y y = new Y();

        y.className = "No class name.";

        y.echoClassName();
    }   

    static class Y { 

        private String className = "Class Name is Y."; 

        public void echoClassName() {

            System.out.println(className);
        }   
    }   
}

Why it shows no error? 为什么没有显示错误?

The scope of a private variable is the whole top level class in which it is enclosed, in your case t . 私有变量的范围是将其包含在其中的整个顶级类,在您的情况下为t See for example JLS #6.6.1 (emphasis mine): 参见例如JLS#6.6.1 (强调我的):

Otherwise, the member or constructor is declared private, and 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. 否则,成员或构造函数将被声明为私有,并且仅当且仅当它出现封装成员或构造函数的声明的顶级类 (第7.6节) 的主体内时,才允许访问。

Y is a nested class. Y是一个嵌套类。 which means it is embeeded in t class, where you run main. 这意味着它嵌入在t类中,在其中运行main。 It is visible for its class only, but if you nest a class with private variable in class, then you can access this variable in this class. 它仅在其类中可见,但是如果您在类中嵌套一个具有私有变量的类,则可以在该类中访问此变量。

If you put Y class in another file and create it in t, then you will get error of visibility. 如果将Y类放在另一个文件中并在t中创建它,则将出现可见性错误。 Since you are using nested class, everything is ok. 由于您使用的是嵌套类,因此一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM