Accessing private variable outside its class in java

China☆狼群 提交于 2019-12-24 16:12:49

问题


The following Java programs compiles successfully. I am expecting an error in the statement y.className = "No class name."; since the private variable className are accessed outside its class.

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?


回答1:


The scope of a private variable is the whole top level class in which it is enclosed, in your case t. See for example JLS #6.6.1 (emphasis mine):

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.




回答2:


Y is a nested class. which means it is embeeded in t class, where you run 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. Since you are using nested class, everything is ok.



来源:https://stackoverflow.com/questions/26486427/accessing-private-variable-outside-its-class-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!