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?
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?
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.
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) { }
}