使用其他接口实现实例化Java中的匿名内部类 [英] Instantiating anonymous inner classes in Java with additional interface implementation
问题描述
比方说,我有以下两个类/接口定义:
Let's say I have the following two class/interface definitions:
public abstract class FooClass {
public abstract void doFoo();
}
和
public interface BarInterface {
public void doBar();
}
如果我想创建一个既扩展又实现了两者的匿名内部类,则需要这样做:
If I want to make an anonymous inner class that extends/implements both, do I need to do this:
public abstract class BothClass extends FooClass implements BarInterface {}
...
new BothClass() {
public void doFoo() {
System.out.println("Fooooooooo!!!!");
}
public void doBar() {
System.out.println("Baaaaaaaar!!!!");
}
}.doBar();
还是有一条捷径可以让我不定义BothClass
?可能是这样的:
Or is there a short-cut that allows me to not define BothClass
? Something like this, maybe:
new (FooClass implements BarInterface)() {
public void doFoo() {
System.out.println("Fooooooooo!!!!");
}
public void doBar() {
System.out.println("Baaaaaaaar!!!!");
}
}.doBar();
(这个想法给了我几个错误,在这里都没有帮助)
(This idea gives me several errors, none of which are helpful here)
推荐答案
匿名类声明是自动从类派生的
Java编译器创建实例创建表达式.
An anonymous class declaration is automatically derived from a class
instance creation expression by the Java compiler. 类实例创建表达式为 因此,不,Java语言规范不允许使用任何快捷方式来使您的匿名类实现比您要键入的类型更多的接口. So, no, the Java language specification does not allow any shortcuts for making your anonymous class implement more interfaces than the type you're sub-typing. 因此,要确定匿名用户的类型课 如果类实例创建表达式以类主体结尾,则
被实例化的类是一个匿名类.然后: If the class instance creation expression ends in a class body, then
the class being instantiated is an anonymous class. Then: [...] 您可以选择的替代方法. Your alternative is the way to do it. 您还可以使用本地类. 这篇关于使用其他接口实现实例化Java中的匿名内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
ClassInstanceCreationExpression:
new TypeArgumentsopt TypeDeclSpecifier TypeArgumentsOrDiamondopt
( ArgumentListopt ) ClassBodyopt
Primary . new TypeArgumentsopt Identifier TypeArgumentsOrDiamondopt
( ArgumentListopt ) ClassBodyopt
TypeArgumentsOrDiamond:
TypeArguments
<>
ArgumentList:
Expression
ArgumentList , Expression