[英]Anonymous extending a class and implementing an interface at the same time?
Suppose I have an interface called Interface, and a concrete class called Base, which, to make thing a bit more complicated, has a ctor that requires some arguments. 假设我有一个名为Interface的接口,以及一个名为Base的具体类,为了使事情变得更复杂,有一个需要一些参数的ctor。
I'd like to create an anonymous class that would extend Base and implement Interface. 我想创建一个扩展Base并实现Interface的匿名类。
Something like 就像是
Interface get()
{
return new Base (1, "one") implements Interace() {};
}
That looks reasonable to me, but it doesn't work! 这对我来说看起来很合理,但它不起作用!
(PS: Actually, the Interface and Base are also generic classes :D. But I'll ignore that for now) (PS:实际上,接口和基础也是通用类:D。但我现在将忽略它)
No, you can't do that with an anonymous class. 不,你不能用匿名类做到这一点。 You can create a named class within a method if you really want to though:
如果你真的想要,你可以在方法中创建一个命名类:
class Base {
}
interface Interface {
}
public class Test {
public static void main(String[] args) {
class Foo extends Base implements Interface {
};
Foo x = new Foo();
}
}
Personally I'd usually pull this out into a static nested class myself, but it's your choice... 就我个人而言,我通常会自己将其拉入静态嵌套类中,但这是您的选择......
This scenario makes little sense to me. 这种情况对我来说没什么意义。 Here's why: assume class
Base
is this: 原因如下:假设类
Base
是这样的:
class Base {
public void foo();
}
and Interface
is this: 和
Interface
是这样的:
interface Interface {
public void bar();
}
Now you want to create an anonymous class that would be like this: 现在,您要创建一个如下所示的匿名类:
class MyClass extends Base implements Interface {
}
this would mean that MyClass
inherits (or possibly overrides) method bar
from Base
and must implement method foo
from Interface
. 这意味着
MyClass
从Base
继承(或可能覆盖)方法bar
,并且必须从Interface
实现方法foo
。 So far so good, your class has these two methods either way. 到目前为止,你的班级有这两种方法。
Now, think what happens when you are returning an object of type Interface
from your method: you only get the functionality that Interface
offers, namely method foo
. 现在,想想当您从方法返回
Interface
类型的对象时会发生什么:您只获得Interface
提供的功能,即方法foo
。 bar
is lost (inaccessible). bar
丢失(无法进入)。 This brings us down to two cases: 这将我们归结为两种情况:
Base
is useless because you do not get to use its methods, since the new object is seen as an Interface
. Base
是没用的,因为你不能使用它的方法,因为新对象被看作是一个Interface
。 Interface
also has a method foo
, but that would mean that Base
itself should implement Interface
, so you can just extend Base
directly: Interface
也有一个方法foo
,但这意味着Base
本身应该实现Interface
,所以你可以直接扩展Base
: class Base implements Interface { public void foo(); public void bar(); } class MyClass extends Base { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.