Can we define an interface within an interface?
Yes.
You could have tested that for yourself and got a completely definitive, opinion-free, risk-free answer in about 30 seconds.
Waiting possibly forever for a possibly incorrect response on a forum is by comparison not a rational mode of enquiry.
We are using it in our application, Interface inside interface, using this basically for being functionality specific constants, so that accidentally no other will create new constants somewhere else in the project, related to this Service1.
example Code:
Public interface Service1{
public interface ServiceInter1{
public Interface In{
Declare your own constants
}
public Interface Out{
Declare your own constants
}
}
}
Yes, we can do it. The definition of the nested interface in java is as follows:
A nested interface is any interface whose declaration occurs within the body of another class or interface. A top-level interface is an interface that is not a nested interface.
Refer this for more.
Further ...
One reason could be that the outer interface has a method that takes a callback implementation as an argument. The nested interface is, in that case, the contract that the callback method must implement. I don't see a reason to declare that callback interface at the top level.
public interface Processor {
void execute(NotificationListener listener);
interface NotificationListener {
void processingCompleted();
}
}
Another good reading at sun site about this topic is here
In particular, notice that when you implement an interface, you are not required to implement any interfaces nested within.
Sure.. Look at SOURCE CODE for java.util.Map interface. Map interface contains a nested Entry interface.
Interestingly, in the source code it simply says
interface Entry <K,V> {
..
}
but the javadoc says
public static interface Map.Entry<K,V>
I guess this is because nested interfaces are implicitly "public static" even though the source code doesn't say that. (But methods inside an interface are implicity public, and cannot be static,that is, only instance methods are permitted in interfaces).
-dbednar 2013-07-02