gpt4 book ai didi

java - 封闭类型的静态嵌套子类仍然可以引用私有(private)字段成员,为什么?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:22:25 25 4
gpt4 key购买 nike

恕我直言,我发现了一些模棱两可的东西。假设我们有以下类结构:

public class A
{
private int privateVar = 1;
protected int protectedVar = 2;

static class B extends A
{
public int getPrivateVariable()
{
return privateVar; //error: Cannot make a static reference to the non-static field memberVariable
}

public int getProtectedVariable()
{
return protectedVar; //OK: Why?
}

public int getPrivateUnfair()
{
return super.privateVar; //Why this can be accessed using super which the protected member doesn't require.
}
}
}
  1. 为什么静态嵌套类可以自由访问实例成员?
  2. 为什么访问protectedprivate 变量的方式不同?但是,如果嵌套类是非静态内部类,情况就不是这样了吗?

编辑:

  1. 为什么允许通过关键字super 访问封闭类型的私有(private)成员?

最佳答案

  1. Why at all does the static nested class has free access to the instance members?

因为 B 扩展了 A。您不是在访问 A 的成员变量,而是在访问 B 的继承成员变量。

  1. Why there is a difference in the way protected and private variables can be accessed? This however, is not the case if the nested class is non-static inner class?

因为私有(private)字段不被继承,而 protected 字段是;但是私有(private)字段仍然存在于父类(super class)中,并且通过 super 可见,因为 B 嵌套在 A 中。可见性修饰符的表达力不足以表达与通过 super 访问相同的内容。

关于java - 封闭类型的静态嵌套子类仍然可以引用私有(private)字段成员,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40653417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com