-1

我需要重构类以提取抽象超类。例如

UpperClass {
NestedClass {
UpperClass.this.someMethod();
}
}

喜欢:

AbstractUpperClass {
    NestedClass {
  ?????.this.someMethod();
  }
}

在我计划在 2 个类 UpperClass1 和 UpperClass2 中继承 AbstractUpperClass 之后。但我不知道如何重构这个内部类,因为它调用了封闭类的方法。有可能吗?谢谢。

4

1 回答 1

0

这里的诀窍是知道内部类是如何工作的。它本质上只是一个“普通”的静态类,但其构造函数隐式获取对封闭类的引用。所以这:

public class TopLevel {

    public void go() {
        new Inner().bar();
    }

    public void foo() { }

    public class Inner {
        public void bar() {
            TopLevel.this.foo();
        }        
    }
}

相当于:

public class TopLevel {

    public void go() {
        new Inner(this).bar();          // explicitly passing in "this"
    }

    public void foo() { }

    public static class Inner {
        private final TopLevel parent;  // note that we have this new field

        public Inner(TopLevel parent) { // note this new constructor
            this.parent = parent;
        }

        public void bar() {             // we use the explicit reference instead
            parent.foo();               // of the implicit TopLevel.this
        }        
    }
}

因此,综上所述,将内部类重构为顶级类的方法是添加一个引用UpperClass实例的显式字段,并将此引用传递给NestedClass构造函数。换句话说,就像第二个代码片段而不是第一个。

于 2012-05-29T16:16:56.640 回答