I like to know can we define an interface within an interface. like
interface abc {
void show();
public interface xyz {
void read();
}
}
This was question asked in interview. Any practical use of this.
An interface can extend any number of interfaces but one interface cannot implement another interface, because if any interface is implemented then its methods must be defined and interface never has the definition of any method.
Java allows declaring interfaces within another interface, these are known as nested interfaces. While implementing you need to refer to the nested interface as outerInterface.
There can be only abstract methods in the Java interface, not the method body. It is used to achieve abstraction and multiple inheritance in Java. In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.
This way, we can only call the nested interface by using outer class or outer interface name followed by dot( . ), followed by the interface name. Example: Entry interface inside Map interface is nested. Thus we access it by calling Map.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With