简体   繁体   English

编译外部类时静态嵌套类的.class文件不能通过关联使用,但可以通过继承使用。 为什么?

[英].class file of static nested class on compiling Outer class can't be used via association but can be used via inheritance. why?

I have an outer class and a static nested class as 我有一个外部类和一​​个静态嵌套类作为

class Outer {
  static int x = 20;
  static class Nested {
    static void show() {
      System.out.println(x);
    }
  }
}

on compiling this program ,I've got two .class files named: Outer.class and Outer$Nested.class . 在编译该程序时,我有两个名为.out的.class文件:Outer.class和Outer $ Nested.class。

Now my question is ,I am trying to use the Outer$Nested.class in my other class Test1 (using association). 现在我的问题是,我正在尝试在其他类Test1中使用Outer $ Nested.class(使用关联)。

class Test1 {
  public static void main(String... args) {
    Outer$Nested i = new Outer$Nested();
  }
}

It gives me compile time error : can't find symbol Outer$Nested. 它给了我编译时错误:找不到符号Outer $ Nested。 And I know we can use static nested class directly as Outer.Nested, but I am just trying this. 而且我知道我们可以将静态嵌套类直接用作Outer.Nested,但我只是在尝试这一点。 But when I am trying to use this class via Inheritance then it is compiling and running fine. 但是,当我尝试通过继承使用此类时,它可以编译并运行良好。

class Temp2 extends Outer$Inner {
  public static void main(String... args) {
    show();
  }
}

Now compiling and running fine , output : 20 现在编译并运行正常,输出:20

So my question is why it is happening that we aren't able to use Outer$Nested via association and event we can't declare variable , but can use via inheritance ? 所以我的问题是,为什么不能通过关联和事件使用Outer $ Nested,而不能声明变量,但是可以通过继承使用呢?

I didn't know how the inheritance concepts works like your way, but want to create instance of the inner nested class use this lines of codes 我不知道继承概念的工作方式与您的方式相同,但想使用此行代码创建内部嵌套类的实例

  public static void main(String[] args){
    Outer.Nested obj= new Outer.Nested();
    obj.show();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么静态嵌套类不能访问外部类的“ this”指针? - Why can't a static nested class access “this” pointer of outer class? 为什么嵌套类不能用作Filter的类 - Why nested class can not be used as class for Filter 可以将静态嵌套类用作jsp bean吗? - Can a static nested class be used as jsp bean? 嵌套类AsyncTask无法修改外部类静态对象 - Nested class AsyncTask can't modify Outer Class static objects 为什么不能将嵌套类的对象用作超类型构造函数的参数? - Why can't object of nested class be used as a parameter of supertype constructor? 为什么以及为什么可以在课堂上使用它? - How and why this can be used with class…? 为什么类不能扩展其中发生的静态嵌套类? - Why can't a class extend a static nested class occurring within it? 为什么这个静态内部类不能在其外部类上调用非静态方法? - Why can’t this static inner class call a non-static method on its outer class? 内部静态类继承内部静态类,子级的外部类也继承父级的外部类,为什么我不能进行强制转换 - Inner static class inherits inner static class, and the outer class of the child also inherits the outer class of the parent, why I can't do casting 为什么Eclipse在另一个类中使用时不能处理@value? - Why can't Eclipse handle @value when used in another class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM