如何调用在外部类的方法中定义的类的实例

Sam*_*011 0 java

class Outer{

    public void Method(){

    int i=10;
    System.out.println(i);
    Class InsideMethod{
        //
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:如何在方法之外调用InsideMethod对象

Ita*_*man 5

这个片段说明了各种可能性:

public class Outer {

  void onlyOuter() { System.out.println("111"); }
  void common() { System.out.println("222"); }

  public class Inner {
    void common() { System.out.println("333"); }
    void onlyInner() {
      System.out.println("444");// Output: "444"
      common();                 // Output: "333"
      Outer.this.common();      // Output: "222"
      onlyOuter();              // Output: "111"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:

  • 内部类的方法隐藏了外部类的类似命名方法.因此,common();调用从内部类调度实现.
  • 使用OuterClass.this构造指定您要从外部类调度方法(绕过隐藏)
  • 调用onlyOuter()调度方法,OuterClass因为这是定义此方法的最内层封闭类.