-1

I started reading an android tutorial and I found an example where I found the following situation:

button.setOnClickListner(new View.OnClickListener() { //SOME CODE} );

Now View.OnClickListener is an interface, then what I understand is that doing in this way I create an instance of an object of OnClickListener type that is formed by the code in the braces. Is it so? But is it a java particular way to make things easier or is it a particular android programming choice? Because I never saw something like this in Java, maybe I didn't study a lot.

zer0uno
  • 7,521
  • 13
  • 57
  • 86

2 Answers2

2

Is it so?

Yes. This is called creating an instance of an anonymous inner class.

But is it a java particular way to make things easier or is it a particular android programming choice?

This is certainly valid Java syntax. I think it may be a bit more popular in Android development than elsewhere, in part based upon Google-supplied code samples. In fact, I have been trying to reduce my use of this idiom in my book, as others found it confusing, as you did.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
2

it's called an anonymous inner class.

it's anonymous because you never actually declare it as a variable, you just call new. It doesn't have a (variable) name so it is anonymous.

It's inner, because it's inside of another class and is not publicly accessible. Well, it can be accessed through button, but that is specific to this usage.

and finally it is a class.

You'll see it in Java everywhere, and it is very common in Android.

Another alternative is to have your class implement that interface, and pass this.

edthethird
  • 6,263
  • 2
  • 24
  • 34