Why should I use anonymous classes in Android instead of overriding the class?

I am new to Android dev. I have read several books about this. And all authors strongly recommend using anonymous classes instead of overriding the class.

They say that

TextView txtTitle; ... txtTitle.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); 

better than

  txtTitle.setOnClickListener(new MyOnClickListener(position)); ... private class MyOnClickListener implements OnClickListener{ ... } 

Can someone explain to me why?

Ofc, if I use the override class for many different objects, this will be a problem for modification.

But if I use my own class only for a specific object, then the logic of my class will not change much, can I use it? Or should I use an anonymous class?

+6
source share
2 answers

An anonymous class will have access to final external variables, so it would be more convenient to use this. For instance:

  final String x = "123"; Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // You can acces "x" here. } }); 

In addition, we are talking about the coding style. Using anonymous can make the code more verbose, but at the same time a little easier to follow.

In addition, a non-anonymous class can be created in several places.

+11
source

Why not implement OnClickListener in the Activity class?

 class MyActivity extends Activity implements OnClickListener 
+3
source

Source: https://habr.com/ru/post/955549/


All Articles