在java中访问其类之外的私有变量 [英] Accessing private variable outside its class in java

查看:35
本文介绍了在java中访问其类之外的私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下Java程序编译成功.我期待语句 y.className = "No class name."; 中出现错误因为私有变量 className 在它的类之外被访问.

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);
        }   
    }   
}

为什么不显示错误?

推荐答案

私有变量的范围是它所包含的整个顶级类,在您的情况下为 t.参见例如 JLS #6.6.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):

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

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.

这篇关于在java中访问其类之外的私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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