Reputation: 12933
I know two ways to use an Interface.
public interface MyInterface {
void myMethod();
}
Approach: Using implements
:
public class MyClass implements MyInterface {
@Override
myMethod(){}
}
I'm using an Interface this way most of the time, if the interface is a contract like:
MyInterface foo = new MyClass();
Now I can control MyClass with the provided methods of the Interface.
This is also nice for collections. If there are some classes which implements MyInterface
I have a common thread:
List<MyInterface> list = new ArrayList<MyInterface>();
Approach: Using it as an anonymous class
:
public class MyClass {
public MyInterface myInterface = new MyInterface(){
@Override
public void myMethod(){}
};
}
This approach I'm using for callbacks with dependcy injection like this:
public class MyOtherClass {
public MyInterface myInterface;
// Using setter injection here
public void setInterface(MyInterface interface){
myInterface = interface;
}
}
MyOtherClass is calling myInterface.myMethod()
where it is appropriate.
A callback can be realized with the first approach by using the this pointer
too. Now I would like to know which approach should be used for a callback and why? I have seen both and I don't know where the real benefit is.
As I see it, that's the only difference where I can choose between the first and second approach. If I'm wrong here please tell me another difference. I'm asking this to be able to select the proper tool for different situations.
In addition I would like to know another situation but a callback, where I can use the second approach.
Upvotes: 1
Views: 136
Reputation: 726619
The choice of using a named or an anonymous interface implementation depends on several things:
In the end, the biggest difference between these two approaches is mostly non-technical: it has to do with readability of your resultant code. After all, anonymous classes are a little more than "syntactic sugar" - you can perfectly implement your system with only named classes. If you think that a named implementation reads better, use the first approach; if you think that an anonymous one works better, use the second approach.
Upvotes: 1