问题描述
我已经看过几个与Java中类似的示例,希望有人可以解释正在发生的事情.似乎可以内联定义一个新类,这对我来说真的很奇怪.
I've seen a couple of examples similar to this in Java, and am hoping someone can explain what is happening. It seems like a new class can be defined inline, which seems really weird to me.
第一个打印输出行应该是预期的,因为它只是toString.但是第二似乎函数可以被内联重写.
The first printout line is expected, since it is simply the toString. However the 2nd seems like the function can be overriden inline.
这是否有技术术语?
还是任何更深入的文档?
Is there a technical term for this?
Or any documentation which goes into more depth?
如果我有以下代码:
public class Apple {
public String toString() {
return "original apple";
}
}
public class Driver {
public static void main(String[] args) {
System.out.println("first: " + new Apple());
System.out.println("second: " +
new Apple() {
public String toString() {
return "modified apple";
}
}
);
}
}
代码输出:
first: original apple
second: modified apple
推荐答案
这是一个匿名内部类.您可以在内部类的Java文档链接中找到有关它的更多信息. . EDIT 我要添加更好的链接描述了匿名内部类,因为Java文档尚待改进. /EDIT
It is an anonymous inner class. You can find some more information about it at the Java documentation link for Inner Classes. EDIT I am adding a better link describing anonymous inner classes, as the Java documentation leaves something to be desired. /EDIT
大多数人将使用匿名内部类来动态定义侦听器.考虑这种情况:
Most people will use Anonymous inner classes to define listeners on the fly. Consider this scenario:
我有一个Button
,当我单击它时,我希望它向控制台显示一些内容.但是我不想在其他文件中创建新类,也不想稍后在该文件中定义内部类,我希望逻辑可以立即在此处使用.
I have a Button
, and when I click it I want it to display something to the console. But I do not want to have to create a new class in a different file, and I don't want to have to define an inner class later in this file, I want the logic to be immediately available right here.
class Example {
Button button = new SomeButton();
public void example() {
button.setOnClickListener(new OnClickListener() {
public void onClick(SomeClickEvent clickEvent) {
System.out.println("A click happened at " + clickEvent.getClickTime());
}
});
}
interface OnClickListener {
void onClick(SomeClickEvent clickEvent);
}
interface Button {
void setOnClickListener(OnClickListener ocl);
}
}
这个例子有些人为的,显然是不完整的,但我认为它可以使想法理解.
The example is somewhat contrived and obviously not complete, but I think it gets the idea across.
这篇关于Java,匿名内部类定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!