java - 内部类变量的可见性

标签 java object inheritance outer-join

我有一个代码-

public class Hello
{
    void create()
    {
        Inner obj=new Inner();
        obj.r=100; //Able to access private variable x
        obj.display(); //displays 100
    }
    class Inner
    {
        private int r=45;
        void display()
        {
            System.out.println("r is : "+r);
        }
    }
    public static void main(String[] args)
    {
        Hello ob=new Hello();
        ob.create();
    }
}

在上面的代码中,通过创建内部类的实例,我们可以访问该类中定义的私有(private)变量。但是继承的情况下却不是这样。为什么会这样?例如,在这个代码-

class One
{
    private int x;
    void getData()
    {
        x=10;
    }
    void display()
    {
        System.out.println("x is : "+x);
    }
}
class Two extends One
{
    int y;
    void putData()
    {
        One o=new One();
        o.x=13; //Error
    }
}
public class File
{
    public static void main(String[] args)
    {
        Two to=new Two();
        to.putData();
    }
}

其背后的确切原因是什么?提前致谢...

最佳答案

请参阅Java Language Specification .

Otherwise, if the member or constructor is declared private, then 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.

这意味着顶级类可以访问其嵌套类的私有(private)成员。

或者换句话说:私有(private)意味着顶级类及其所有嵌套类私有(private),而不是嵌套类本身私有(private)。

关于java - 内部类变量的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32289331/

相关文章:

java - 在android中保存字符串的最后4个字符

java - 泛型和原始类型

JavaScript - 等待所有 array.push() 完成后再返回函数

java - 如何检查不同类中的变量是否已更新?

java - 使用数组从文本文件创建对象(无ArrayList),运行时出现InputMismatchException

java - 从类和接口(interface)重新继承静态字段

java - Java 与 Python 中的局部变量作用域

java - 知道何时调用监听器的方法

javascript - 如何检查子类是否覆盖了父类的方法/函数?

java - 从接口(interface)对象转换为实现它的类的对象?