有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是否可以从嵌套类引用outter类指针?

我需要在内部类中使用外部类的this指针

我不知道如何在不保存this指针的情况下进行操作。还有别的选择吗

class outerclass {

  outerClass thisPointer;

  outerclass () {
      //
      // NOTE: I am saving this pointer here to reference
      // by the inner class later.   I am trying to find
      // a different alternative instead of saving this pointer.
      //
      thisPointer = this; 
  }

  class innerClass {

      void doSomething () {

           //
           // is there a way to reference the outter class
           // without having to save the thisPointer from
           // the outter class.
           // NOTE someObject is a class outside of the
           // outterclass control.
           //
           someObject.someMethod (thisPointer);
      }
  }     
}  

共 (2) 个答案

  1. # 1 楼答案

    使用语法NameOfOuterClass.this

    void doSomething () {
        someObject.someMethod(outerClass.this);
    }
    
  2. # 2 楼答案

    outclass.this 
    

    我们应该做到这一点

    我假设你的外部类名是outerclass。按照Java的惯例,类名应该以大写字母开头

    如果我没有正确理解你的例子,那么这里有一些示例代码。这里,外部类(Test1)中a的值被分配给内部类(Test2)中的局部变量

    public class Test1  {
    
        private int a =42;         
    
        private class Test2 {
    
             public void a() {
                 int i = Test1.this.a;
             }
    }