0

Considering OnCompleteListener is an interface and OnCompleteListenerImpl is a concrete class as follows

### OnCompleteListener interface ####

public interface OnCompleteListener {

    public void onComplete();
}

#### OnCompleteListenerImpl ####

class OnCompleteListenerImpl  implements OnCompleteListener {
    public void onComplete() {    
        System.out.println("Yeah, the long running task has been completed!");
    }
}

How is this

#### Snippet A #####

longRunningTask.setOnCompleteListener(new OnCompleteListener() {

        @Override
        public void onComplete() {
            System.out.println("Yeah, the long running task has been completed!");
        }
    }
);

different from

#### Snippet B ######

OnCompleteListenerImpl obj = new OnCompleteListenerImpl();

longRunningTask.setOnCompleteListener(obj);
Madplay
  • 1,027
  • 1
  • 13
  • 25
anoop
  • 47
  • 5
  • This is the same. Just if you use it many times, Prefer the OnCompleteListenerImpl solution. – azro Nov 01 '19 at 09:36
  • 3
    Pretty much the same, although `Snippet A` is creating an anonymou class, instead of a named one.... you may want to take a look at https://stackoverflow.com/questions/38387541/what-is-the-use-case-and-advantage-of-anonymous-class-in-java and https://stackoverflow.com/questions/355167/how-are-anonymous-inner-classes-used-in-java – lealceldeiro Nov 01 '19 at 09:38

1 Answers1

0

Both are approaches are similar but there is a big difference between

Usability

  1. Class OnCompleteListenerImpl is reuseable, you need not override the same object multiple places
  2. You need to be careful while initializing OnCompleteListenerImpl object, as you can initialize in multiple ways, you have to be careful with its scope.
  3. You need not create a new implementation class if you are going with an anonymous approach.

In summary, there are different use cases for both the approaches it is up to you which one you want to follow. For clean code and reusability, we go with implementation class but in case of secure and single instance use, you can go with anonymous class approach.

Kushagra Misra
  • 461
  • 1
  • 7
  • 15