Creating object from OnClickListener interface

六月ゝ 毕业季﹏ 提交于 2019-12-22 18:26:22

问题


OnClickListener is an static interface but I am instantiating from OnClickListener.

I'm confused and wondering that can we generate objects from interface in java?

Why don't we create concrete class, inherit from OnClickListener interface?


回答1:


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.

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.




回答2:


You are not instantiating the interface. What you're doing with the following code is directly creating an implementation of the Interface and store it in the tv_onClick variable..

private OnClickListener tv_onClick = new OnClickListener() {
   public void onClick(View arg0) { }
}


来源:https://stackoverflow.com/questions/7085999/creating-object-from-onclicklistener-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!