2

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? enter image description here

enter image description here

X.Y.
  • 13,726
  • 10
  • 50
  • 63
uzay95
  • 16,052
  • 31
  • 116
  • 182
  • 1
    what is a static interface? You are not generating an object from the interface, you are actually creating an inline implementation of the interface... – DeyyyFF Aug 16 '11 at 22:54
  • _Why don't we create concrete class, inherit from OnClickListener interface?_ That's exactly what is happening, only in a shorthand notation. – biziclop Aug 16 '11 at 22:57
  • But there is new word. new OnClickListener is equal class Hoob implements OnClickListener ? new word is using to generate an object isn't it? – uzay95 Aug 16 '11 at 23:24
  • Yes it is equal to class Hoob implements OnClickListener. Yeah, new is normally generating a new object. But in that case you're creating a anonymous inner class, like Tom G wrote in his answer. – Prine Aug 16 '11 at 23:40

2 Answers2

5

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.

Thorn G
  • 12,620
  • 2
  • 44
  • 56
  • Yeah, I forget where I did eventually end up reading that, but it wasn't immediately obvious from the Sun docs. I'm guessing it's specified more precisely in the actual language spec. – Thorn G Aug 17 '11 at 00:07
1

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) { }
}
Prine
  • 12,192
  • 8
  • 40
  • 59