为什么私有变量可以从静态嵌套类外部访问?

huangapple 未分类评论53阅读模式
英文:

Why are private variables accessible from outside a static nested class?

问题

以下是翻译好的内容:

我在理解这个实例中 private 关键字的行为方面遇到了一些困难:

public class OuterClass {
    static class StaticNestedClass {
        private int a = 4;
        // 从类外部不应该可以访问
    }
    public static void main(String[] args) {
        StaticNestedClass c = new StaticNestedClass();
        System.out.println(c.a);
        // 尽管 a 是私有的,这个语句却打印出了 a 的值
    }
}

与其返回编译错误不同,主方法能够访问变量 a,即使它是私有的。为什么会这样呢?

此外,是否有其他方法使嵌套类内部的某些变量对主方法不可访问?

编辑
请注意,这个问题涉及的是 静态嵌套类,而不是内部类,因此作用域规则应该是不同的。

英文:

I am having some trouble understanding the behavior of the private keyword in this instance:

public class OuterClass {
         static class StaticNestedClass {
              private int a = 4; 
              // Should not be accessible from outside the class
         }
         public static void main(String[] args) {
              StaticNestedClass c = new StaticNestedClass();
        	  System.out.println(c.a); 
              // This statement prints the value of a, even though b is private
         }
}

Instead of returning a compiler error, the main method is able to access the variable a, even though it is private. Why does it do this?

Also, is there any other way to make certain variables inside the nested class inaccessible to the main method?

EDIT
Note that this question is about static nested classes, not inner classes, and so the scope rules should be different.

huangapple
  • 本文由 发表于 2020年4月6日 01:01:58
  • 转载请务必保留本文链接:https://java.coder-hub.com/61046249.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定