【问题标题】:How to access outer outer class(not outer class) property?如何访问外部外部类(不是外部类)属性?
【发布时间】:2015-08-05 06:39:15
【问题描述】:

例如,如果 A 有内部类 B,B 有内部类 C,都有一个属性“name”,我知道 C 可以通过 B.this.name 访问 B 中的 name,但是如何从 A 中访问 name C?

public class A{
    String name="A";
    public class B{
        String name="B";
        public class C{
            String name="C";
            public C(){
                //how to print name in A?
                //System.out.println(B.A.name);
                //System.out.println(B.A.this.name);
                //System.out.println(B.this.A.name);
                //System.out.println(B.this.A.this.name);
            }
        }
        C c=new C();
    }
    B b=new B();
    public static void main(String[] args){
        new A();
    }
}

试了很多语法都编译不出来,搜索java外部类的时候发现大部分都是关于外部类的,不是外部外部类的。

【问题讨论】:

  • 你为什么要创造这么多复杂性?
  • 如果您确实需要这些嵌套类,请将“A”传递给“B”构造函数,并将“B”传递给“C”构造函数
  • @DiSaSteR,这里没有继承。 super() 将调用 Object 类的构造函数。

标签: java syntax inner-classes outer-classes


【解决方案1】:

使用A.this.name 访问最外层的类。或任何其他课程。

【讨论】:

    【解决方案2】:

    使用System.out.println(A.this.name);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 2016-03-13
      • 2015-06-09
      • 2014-08-10
      • 1970-01-01
      • 2011-01-02
      相关资源
      最近更新 更多