Why do we need inner interfaces, especially with the private access modifier?

Harsh Chaturvedi :

I am new to Java. Recently I read about inner interfaces and it's very confusing to me: first why they are used, and second why they can be declared private too as opposed to outer interfaces. In my opinion interfaces should be public so that they can be used by all.

Lahiru Wijesekara :

Purpose of an inner interfaces in java as below

  1. solving the namespacing issue when the interface has a common name
  2. increasing encapsulation
  3. increasing readability by grouping related interfaces in one place.

A nested interface can be declared as public, private, or protected. This differs from the top-level interface.The top-level interface must either be declared as public or use the default access level.

Declaration of an inner interface in the body of another interface.

public interface Items {
            interface MyList {
            }
        }

Declaration of an inner interface in the body of another class.

 public class Items{
                public interface MyList {
                    void add(Items items);
                    String getItesmNames();
                }
        }

Finally, we can Implement as per below

public class SpecialItems implements Items.MyList  {

}

When a nested interface is used outside of its enclosing scope, it must be qualified by the name of the class or interface of which it is a member.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=134319&siteId=1