这种类型的方法重写在 Java 中被称为什么?
我对 Java 比较陌生,并且正在使用新的 API。我遇到了这个方法重写,但我不确定它叫什么:
public void exampleMethod() {
Button loginButton = new Button("login"){
public void onSubmit(){
//submit code here
}
};
}
根据我的理解,这是重写 Button 类的 onSubmit 方法。我以前从未遇到过这种类型的覆盖。它有具体的名称吗?我想阅读更多相关内容,但找不到。到目前为止,我所有的搜索结果都是通过创建一个新类来覆盖常规方法,这是我已经熟悉的。
如果有人能指出我正确的方向,我将不胜感激。
谢谢。
I'm relatively new to Java and I'm using a new API. I came across this method override and I'm not sure what this is called:
public void exampleMethod() {
Button loginButton = new Button("login"){
public void onSubmit(){
//submit code here
}
};
}
From what I understand, this is overriding the onSubmit method of the Button class. I've never come across this type of overriding before. Is there a specific name for it? I want to read up more about it but I can't find it. All my searches so far result to regular method overriding by creating a new class, which is what I'm already familiar with.
I'd appreciate if someone could point me in the right direction.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个匿名内部类。
在上面的示例中,我们没有创建扩展
Button
的私有类
,而是创建 Button 的子类,并提供与其余代码一致的重写方法的实现。由于这个新类是动态创建的,因此它没有名称,因此是匿名。由于它是在另一个类中定义的,因此它是一个匿名内部类。
它可能是一个非常方便的快捷方式,特别是对于
Listener
类,但如果您忘乎所以并且内联方法定义太长,它可能会使您的代码难以理解。That's an anonymous inner class.
In the example above instead of creating a
private class
that extendsButton
we create an subclass of Button and provide the implementation of the overridden method in line with the rest of the code.As this new class is created on the fly it has no name, hence anonymous. As it's defined inside another class it's an anonymous inner class.
It can be a very handy shortcut, especially for
Listener
classes, but it can make your code hard to follow if you get carried away and the in line method definitions get too long.这是一个匿名内部类。基本上,它创建一个派生自指定类的新类(在本例中为
Button
,尽管您可以使用相同的技术来实现接口)并重写适当的方法。它也可以包含其他方法,但它们只能在该类中使用。该类可以访问同一方法中的最终局部变量,如果您正在编写一个实例方法,它也可以隐式引用
this
(因此您可以在“main”中调用其他方法)班级)。That's an anonymous inner class. Basically it creates a new class which derives from the specified one (
Button
in this case, although you can use the same technique to implement interfaces) and overrides appropriate methods. It can contain other methods as well, but they'd only be available within that class.The class has access to final local variables within the same method, and if you're writing an instance method it has an implicit reference to
this
as well (so you can call other methods in your "main" class).那是一个匿名内部类。
更多信息:匿名类
That is an anonymous inner class.
More info: Anonymous classes