tags:

views:

394

answers:

2

Hi , 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 real time use of this.

+12  A: 

Yes we can do it. The definition of 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 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 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.

HotTester
@girinie I think you should accept HotTester's answer but for a real time use of it, look at Map and Map.Entry. The Map.Entry interface is part of the protocol for a Map (used when returning from Map.entrySet() ), hence it is part of the Map interface. (While writing this, HotTester added similar info to the answer, +1)
Fredrik
@Fredrik s/real time/real life/p :-)
Stephen C
@HotTester.. thanks for the update i really didn't knew it was possible !
@Stephen C Of course... I must have had my mind somewhere else when writing, I have no other explanation.
Fredrik
+2  A: 

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.

EJP
+1 Such laziness on the part of question submitters isn't good for anyone.
Kevin Bourrillion
+1 But it's all part of the game of increasing rep points.
Kirk Broadhurst