Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using anonymous classes when calling interfaces

Tags:

java

android

I'm trying to fully integrate the concept of anonymous classes and interfaces in Android and Java. In another thread a reply was given to a question regarding something like:

getQuote = (Button) findViewById(R.id.quote);

getQuote.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        // Do something clever
    }
}

"What is sent in there is an anonymous class, you could just as well make a separate class which implements OnClickListener and make an instance of that class and send that in as the argument to setOnClickListener." -- Jon

My question is what would the code look like if you went the long route of creating a separate class that implements OnClickListener? I think if I saw the long route it would make more sense. Many thanks!

like image 514
PonziCoder Avatar asked Dec 29 '25 02:12

PonziCoder


1 Answers

class MyClass implements View.OnClickListener {

    @Override
    public void onClick(View v) {

        // Do something clever
    }

}

// Calling Code

MyClass listener = new MyClass();
getQuote.setOnClickListener(listener);

When you're creating a lot of them and as they're not required apart from where you declare and bind it then the anonymous class is considered a neater approach.

like image 200
planetjones Avatar answered Dec 31 '25 14:12

planetjones