Java 中的静态嵌套类和非静态嵌套类
class OuterClass {
private static String msg = "GeeksForGeeks";
public static class NestedStaticClass {
public void printMessage() {
System.out.println("Message from nested static class: " + msg);
}
}
public class InnerClass {
public void display() {
System.out.println("Message from non-static nested class: " + msg);
}
}
}
public class Main {
public static void main(String args[]) {
OuterClass.NestedStaticClass printer = new OuterClass.NestedStaticClass();
printer.printMessage();
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display();
OuterClass.InnerClass innerObject = new OuterClass().new InnerClass();
innerObject.display();
}
}
运行结果
```
Message from nested static class: GeeksForGeeks
Message from non-static nested class: GeeksForGeeks
Message from non-static nested class: GeeksForGeeks
```
Message from nested static class: GeeksForGeeks
Message from non-static nested class: GeeksForGeeks
Message from non-static nested class: GeeksForGeeks
```
public class ShadowTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
System.out.println("x = " + x);
System.out.println("this.x = " + this.x);
System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
}
}
public static void main(String... args) {
ShadowTest st = new ShadowTest();
ShadowTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
}
}
运行结果
```
x = 23
this.x = 1
ShadowTest.this.x = 0
```
x = 23
this.x = 1
ShadowTest.this.x = 0
```
参考资料