java - 为什么此私有静态变量能被访问呢?
高洛峰
高洛峰 2017-04-18 10:47:37
0
11
1472
class Test{
    private static int i = 1;
    
    public static void main(String[] args){
        Test test = new Test();
        System.out.println(test.i);  //此处为何能访问到私有的i变量呢?
    }
}

如果与Test类不同包,调用i变量却报错,为何?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(11)
小葫芦

Theoretically, access modifiers are not completely necessary and will not affect program logic. This is only during the compilation phase to help programmers write safer code.
I understand the confusion of the questioner. He thinks it is more appropriate to use this.i here (of course, remove the crappy static keyword). This view may be true. It can make some people go crazy. this.i较为妥当(当然,去掉那个蹩脚的static关键字吧),这个观点可能还真会使一些人走火入魔。
记住:这些访问修饰符与执行上下文无关,比如privateRemember: These access modifiers have nothing to do with the execution context. For example, private will only check whether the code you use to access this variable is written in the current class at compile time. It is as simple and crude as that.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template