Reputation: 5193
When to implement interface in class and when to instantiate an anonymous implementation of an interface. Below are two interfaces.
public interface InterfaceOne {
void one();
}
public interface InterfaceTwo {
void two();
}
Approach 1: Implement interface in class
public class A implements InterfaceOne, InterfaceTwo {
private void doSomething() {
Hello hello = new Hello();
hello.hi(this);
hello.bye(this);
}
@Override
public void one() {
//One
}
@Override
public void two() {
//Two
}
}
Approach 2: Instantiate an anonymous implementation of an interface
public class B {
private void doSomething() {
Hello hello = new Hello();
hello.hi(interfaceOne);
hello.bye(interfaceTwo);
}
private InterfaceOne interfaceOne = new InterfaceOne() {
@Override
public void one() {
//One
}
};
private InterfaceTwo interfaceTwo = new InterfaceTwo() {
@Override
public void two() {
//Two
}
};
}
What are the scenarios in which we need to use Approach 1 and Approach 2?
Upvotes: 0
Views: 48
Reputation: 133587
With Java8 things slightly changed because with functional interfaces you are allowed to define lambdas with are internally managed as anonymous classes so the awkward syntax is somewhat saved.
In any case an anonymous class makes sense only when you are dealing with something which doesn't need to be named (think about an ActionListener
for a button). A named class instead always makes sense, there is no explicit reason to avoid naming a class.
Upvotes: 1