Nested interface:
An interface which is declared inside another interface or class is called nested interface. They are also known as inner interface.
Since nested interface cannot be accessed directly, the main purpose of using them is to resolve the namespace by grouping related interfaces (or related interface and class) together.
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.
Note:
- Nested interfaces are static by default. You don’t have to mark them static explicitly as it would be redundant.
- Nested interfaces declared inside class can take any access modifier, however nested interface declared inside interface is public implicitly.
Example 1: Nested interface declared inside another interface-
Entry interface inside Map interface is nested. Thus we access it by calling Map.Entry.
public interface Map {
interface Entry{
int getKey();
}
void clear();
}
public class MapImpl implements Map {
class ImplEntry implements Map.Entry{
public int getKey() {
return 0;
}
}
@Override
public void clear() {
//clear
}
}Why Use Inner Interface?
There are several compelling reasons for using inner interface:
- It is a way of logically grouping interfaces that are only used in one place.
- It increases encapsulation.
- Nested interfaces can lead to more readable and maintainable code.
Example 2: Nested interface declared inside a class
Inner interfaces declared within another class are also static, but they can have access specifiers which can constrain where they can be implemented:
Example 1:
class Design{
interface Message{
void dispaly();
}
}
class NestedDemo implements Design.Message{
public void dispaly(){
System.out.println("nested interface");
}
public static void main(String args[]){
Design.Message message = new NestedDemo();//upcasting here
message.dispaly();
}
}
Output: nested interface
Example 2:
public class Customer {public interface List {
void add(Customer customer);
String getCustomerNames();
}
//rest of the code
}
In the example above, we have a List interface which will serve as declaring some operations on list of Customers such as adding new ones, getting a String representation and so on.
List is a prevalent name, and to work with other libraries defining this interface, we need to separate our declaration, i.e., namespace it.
This is where we make use of an inner interface if we don't want to go with a new name like CustomerList. We also kept two related interfaces together which improves encapsulation.
public class CommaSeparatedCustomers implements Customer.List {
// ...
}
Comments
Post a Comment