Why use implements?

9

What's the difference between using

btn.setOnClickListener(new OnClickListener() {

and

public class MainActivity extends Activity implements OnClickListener{

I've been doing an Android course and my teacher said that implements only helps to leave the code clean without making it necessary to use OnClickListener in the middle of the code. Is it just this?

    
asked by anonymous 27.06.2014 / 02:31

1 answer

11

The purpose of implements is not to leave the code cleaner , it's just a reserved word that says your class is implementing an interface, that is, your class is now the type that it has implemented, with this comes what we usually call the "Contract", which is a way of saying that the class that implements the interface is required to implement all the methods that the interface has declared.

Analyzing your case. In:

btn.setOnClickListener(new OnClickListener() {

You are creating an anonymous class that must follow the contract imposed by the OnClickListener interface.

In:

public class MainActivity extends Activity implements OnClickListener{

You have your MainActivity class implement the OnClickListener interface.

In both cases you will need to override the onClick(View v) method. Obviously, in the first case you will need to do this within your anonymous class and in the second case it will fall within your MainActivity class.

If this will leave the code cleaner or not, it depends, it can do this if you have numerous buttons that may have something in common, so it is advantageous that they all call the same method onView() within its MainActivity class , like this:

btn.setOnClickListener(this);

However, it does not make much sense for multiple buttons to do exactly the same thing, which is why I said that it can be used when they have similar functions, but doing so will need to check inside the implemented method which button was called , so usually within this method you will have switch or several if s.

To the point that, if your class did not implement it you would have to "replicate" the code for all your buttons. So:

btn.setOnClickListener(new OnClickListener() {
    //faça alguma coisa
});

If you only have one button, the situation is almost tied, because you will only implement it once. For both cases the difference will be more your satisfaction with each of the ways to solve the problem.

More details on what an interface is and why it is useful can be found in this other answer: In Object Orientation, why are interfaces useful?

    
27.06.2014 / 02:44