简体   繁体   中英

.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 .

Now my question is ,I am trying to use the Outer$Nested.class in my other class Test1 (using association).

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. And I know we can use static nested class directly as Outer.Nested, but I am just trying this. 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

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 ?

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();
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM