gpt4 book ai didi

java - 使用附加接口(interface)实现在 Java 中实例化匿名内部类

转载 作者:搜寻专家 更新时间:2023-11-01 01:34:47 25 4
gpt4 key购买 nike

假设我有以下两个类/接口(interface)定义:

public abstract class FooClass {
public abstract void doFoo();
}

public interface BarInterface {
public void doBar();
}

如果我想制作一个扩展/实现两者的匿名内部类,我是否需要这样做:

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?可能是这样的:

new (FooClass implements BarInterface)() {
public void doFoo() {
System.out.println("Fooooooooo!!!!");
}

public void doBar() {
System.out.println("Baaaaaaaar!!!!");
}
}.doBar();

(这个想法给了我几个错误,在这里都没有帮助)

最佳答案

Let's go to the JLS:

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 语言规范不允许使用任何快捷方式来让您的匿名类实现比您正在子类型化的类型更多的接口(interface)。

所以,到determine the type of the anonymous class

If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class. Then:

  • If T denotes an interface, then an anonymous direct subclass of Object that implements the interface named by T is declared.

[...]

  • 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.

您的替代方案是实现它的方式。

您还可以使用 local classes.

关于java - 使用附加接口(interface)实现在 Java 中实例化匿名内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21515693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com