使用其他接口实现实例化Java中的匿名内部类 [英] Instantiating anonymous inner classes in Java with additional interface implementation

查看:168
本文介绍了使用其他接口实现实例化Java中的匿名内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有以下两个类/接口定义:

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.

类实例创建表达式为

ClassInstanceCreationExpression:
    new TypeArgumentsopt TypeDeclSpecifier TypeArgumentsOrDiamondopt
                                                            ( ArgumentListopt ) ClassBodyopt
    Primary . new TypeArgumentsopt Identifier TypeArgumentsOrDiamondopt
                                                            ( ArgumentListopt ) ClassBodyopt

TypeArgumentsOrDiamond:
    TypeArguments
    <> 

ArgumentList:
    Expression
    ArgumentList , Expression

因此,不,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:

  • 如果T表示接口,则Object的匿名直接子类 声明了实现由T命名的接口的子程序.
  • If T denotes an interface, then an anonymous direct subclass of Object that implements the interface named by T is declared.

[...]

  • 让T为由标识符和任何类型参数命名的类型.一个 声明由T命名的类的匿名直接子类.这 子类的主体是类实例中给定的ClassBody 创建表达.
  • Let T be the type named by the Identifier and any type arguments. An anonymous direct subclass of the class named by T is declared. The body of the subclass is the ClassBody given in the class instance creation expression.

您可以选择的替代方法.

Your alternative is the way to do it.

您还可以使用本地类.

这篇关于使用其他接口实现实例化Java中的匿名内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆