java – Why nested interfaces?

Question:

Walking through other people's codes, I came across a Class that contains interfaces inside:

class Aborigen{

interface Arm{
}

interface Hand{
}

//..etc code
}

Where it can be necessary in practical application?
I also encountered when there are classes inside the interface.
This is something new for me. I'm confused.

Answer:

For example, when you need to bind an interface to a specific class.

Classic example (from android world) View.OnClickListener

The bottom line is that OnClickListener is such an abstract name that can be attached to a lot of things, and in this case it is clearly understood that this OnClickListener interface refers specifically to View

Either this interface is needed exclusively within this class (well, you never know) and it is not taken out, so as not to produce unnecessary entities and confuse readers.

By and large, this is just another layer of code isolation and organization. There is another classic example (albeit with classes, but the essence is the same) – these are builder classes.

You can make two files/classes: MyObject and MyObjectBuilder , but it's more… elegant, or something, to call MyObjectBuilder just Builder , put it inside MyObject and call it as MyObject.Builder

Scroll to Top