在匿名类中定义自定义函数/属性

SimpleGuy:

我想在匿名类中定义我的属性和函数,如下

ExistingExtendableJavaClass aClass = new ExistingExtendableJavaClass() {
         public String someProperty;

         public String getMyProperty() { return someProperty }
});

但是后来这些电话不起作用

aClass.someProperty // not accessible
aClass.getMyProperty() // not accessible

我知道是因为ExistingExtendableJavaClass没有这些,但后来我的匿名者有了这些。我怎样才能做到这一点?

rzwitserloot:

可以很好地访问它们:

new ExistingExtendable() {
    public void foo() {}
}.foo();

效果很好。

但是,如果您写:

ExistingExtendable x = new ExistingExtendable() {
    public void foo() {}
};
x.foo();

那行不通。出于同样的原因,这不起作用:

Object o = new String();
o.toLowerCase(); // nope

问题在于您的匿名类没有名称,因此,您不能表示其类型。我们可以通过更换固定字符串例子Object oString o,但没有String等同的。

但是,这就是匿名内部类的要点

如果您希望它们是可表示的,那么您就不需要匿名的内部类。问:“我想要一个匿名内部类,但我希望在其中声明的新成员可以访问”,就像问:“我想要一个圆,但是..带有角”。

您可以使方法成为本地内部类,现在有了名称:

public void example(String x) {
    class IAmAMethodLocalClass extends ExistingExtendableJavaClass {
        String someProperty; // making them public is quite useless.

        String foo() {
            System.out.println(x); // you can access x here.
        }
    }

    IAmAMethodLocalClass hello = new IAmAMethodLocalClass();
    hello.someProperty = "It works!";
}

匿名内部类与此方法本地类相同,只是它避免了命名类型。在这种情况下,您需要该名称,因此,您不能使用匿名内部类构造。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章