Interface inside Class
Q1. Can I have an interface insi开发者_运维知识库de a class in java?
Q2. Can I have an class inside an interface?
If yes, then in which situations should such classes/interfaces used.
Q1. Yes Q2. Yes.
Inside your class you may need multiple implementations of an interface, which is only relevant to this particular class. In that case make it an inner interface, rather than a public / package-private one
In your interface you can define some data holder classes that are to be used by implementations and clients.
One example of the latter:
public interface EmailService {
void send(EmailDetails details);
class EmailDetails {
private String from;
private String to;
private String messageTemplate;
// etc...
}
}
I have faced providing common complex operations for all classes implementing an interface, that use obviously the operations of the interface.
Until Java 8 is not out...
See http://datumedge.blogspot.hu/2012/06/java-8-lambdas.html (Default Methods)
A workaround for this is:
public interface I
{
public Class U{
public static void complexFunction(I i, String s){
i.f();
i.g(s)
}
}
}
Then you can easily call common functionality (after importing I.U)
U.complexFunction(i,"my params...");
May further refined, with some more typical coding:
public interface I
{
public Class U{
I me;
U(I me){
this.me = me;
}
public void complexFunction(String s){
me.f();
me.g(s)
}
}
U getUtilities();
}
class implementationOfI implements I{
U u=new U(this);
U getUtilities(){ return u; }
}
calling then
I i = new implementationOfI();
i.getUtilities().complexFunction(s);
A further spicy tricks
- is providing U as abstract, giving the chance for local implementation of certain functions for U...
- reimplementing U with a local class and local constructor using I.this instead of forcing parameter pass...
- using a static U... however then each operation must get I i as parameter...
- using enum instead of class, for static functions only, not requiring any further objects (equivalent to the first method)
The reason for this is to put the operations into a single module instead of having utilities modules hanging around, allowing extendable the worst, duplicated implementation.
精彩评论