问题描述
OnClickListener是一个静态的界面,但我从OnClickListener实例。
OnClickListener is an static interface but I am instantiating from OnClickListener.
我很困惑,不知道能我们在java中生成接口的对象?
I'm confused and wondering that can we generate objects from interface in java?
我们为什么不创造具体的类,从OnClickListener接口继承?
Why don't we create concrete class, inherit from OnClickListener interface?
推荐答案
这就是被称为一个的匿名内部类的。对Java标准版Swing的文档涵盖它here,和我想象它是用于在很多Android开发同样的目的。它可以让你更简单地挂上各种事件处理程序接口的火这些事件的组件。例如,如果在这个OnClickListener正在执行时从来不需要其他地方的动作,你现在它仅限于它被使用的唯一类。你不需要在你的源代码树的另一个类文件,这是一个有点更加明显发生了什么事在那个特定的UI组件。
That is what is known as an anonymous inner class. The Swing documentation for Java Standard Edition covers it here, and I imagine it's used for much the same purpose in Android development. It allows you to more simply hook up various event handler interfaces to the components that fire those events. For example, if the action being performed in this OnClickListener is never needed anywhere else, you've now restricted it to the only class where it gets used. You don't need another class file in your source tree and it's a little more obvious what's going on in that particular UI component.
在幕后,编译器使用自动生成的名称,它确实落实 OnClickListener
创建类。你可能会在堆栈跟踪有时会看到这一点,有一个名为类 com.foo.Class $ 1
。这 $ 1
是编译器生成的类。
Behind the scenes, the the compiler is creating a class with an automatically generated name, which does indeed implement OnClickListener
. You might see this sometimes in a stack trace, with a class named com.foo.Class$1
. That $1
is what the compiler generates for your class.
这篇关于从OnClickListener接口创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!