android - Can someone please explain me with an example how interface can be used as a method parameter in Java? -


clicking button in android:

final button savebutton = (button) findviewbyid(r.id.savebutton); savebutton.setonclicklistener(new onclicklistener(){  public void onclick(view v){}  savebutton.settest("clicked") } 

onclicklister interface passed inside methodd setonclicklistener, unsure how working?

what see there called anonymous class (you've chopped bit off end, though). it's not instance of interface (interfaces can't have instances), although looks bit one. code creates class implements interface given onclick method, , creates instance of class pass setonclicklistener, in 1 new expression.

anonymous classes meant situations need one-off instance pass method accepts interface. rather making write separate class definition, several years (java 5, think was) added ability define class , create instance on-the-fly that.

the code in onclick method has access final variables in method it's created.


the link above java tutorial on anonymous classes.


Comments

Popular posts from this blog

c - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -