Java syntax Internal interface Learning--what is Inner Interface in Java?

Source: Internet
Author: User

What's Inner Interface in Java?

Inner interface is also called nested interface, which means declare an interface inside of another interface. For example, the Entry interface are declared in the Map interface.

 Public Interface Map {    interface  entry{        int  getKey ();    }      void clear ();}

Why use Inner Interface?

There is several compelling reasons for using inner interface:

    • It is a-a-logically grouping interfaces that was only used in one place.
    • It increases encapsulation.
    • Nested interfaces can leads to more readable and maintainable code.

One example of inner interface used in the Java standard library is java.util.Map and Java.util.Map.Entry. Here Java.util.Map is used also as a namespace. Entry does not belong to the global scope, which means there is many other entities that is Entries and is not Necessar Y Map ' s entries. This indicates, Entry represents entries related to the MAP.

How Inner Interface Works?

Inner interface Works, we can compare it with nested classes. Nested classes can be considered as a regular method declared in outer class. Since a method can be declared as static or non-static, similarly nested classes can be static and non-static. Static class is as a static method, it can only access outer class members through objects. Non-static class can access any member of the outer class.

Because an interface can isn't instantiated, the inner interface only makes sense if it's static. Therefore, by default inter interface are static, no matter you manually add static or not.

A simple Example of Inner Interface?

Map.java

 Public Interface Map {    interface  entry{        int  getKey ();    }      void clear ();}

Mapimpl.java

 Public class Implements Map {      classimplements  map.entry{        publicint   GetKey () {            return 0;        }            }     @Override    publicvoid  Clear () {        //Clear     }}

Thinking in Java

Interfaces May is nested within classes and within other Interfaces. This reveals a number of very interesting features:

//: C08:nesting:NestingInterfaces.java Packagec08.nesting;classAInterfaceBvoidf (); } Public classBimpImplementsB Public voidF () {}}Private classBImp2ImplementsB Public voidF () {}} Public InterfaceCvoidf (); }classCimpImplementsC Public voidF () {}}Private classCImp2ImplementsC Public voidF () {}}Private InterfaceB =voidf (); }Private classDimpImplementsB = Public voidF () {}} Public classDImp2ImplementsB = Public voidF () {}} PublicD getd () {return NewDIMP2 (); }PrivateD DRef; Public voidReceiveD (d d) {dRef = D;  DREF.F (); }}InterfaceEInterfaceGvoidf (); }//Redundant "public":   Public InterfaceHvoidf (); }voidg ();//cannot is private within an interface:  //! Private interface I {}} Public classnestinginterfaces { Public classBimpImplementsA.B { Public voidF () {}}classCimpImplementsA.C { Public voidF () {}}//cannot implement a private interface except  //Within that interface ' s defining class:  //! class Dimp implements A.D {  //! public void F () {}  //! }  classEimpImplementsE Public voidg () {}}classEgimpImplementse.g { Public voidF () {}}classEImp2ImplementsE Public voidg () {}classEGImplementse.g { Public voidF () {}}} Public Static voidMain (string[] args) {A A =NewA ();//Can ' t access A.D:    //! A.D ad = a.getd ();    //doesn ' t return anything but A.D:    //! A.DIMP2 Di2 = a.getd ();    //cannot access a member of the interface:    //! a.getd (). f ();    //Only another A can does anything with getd ():A A2 =NewA ();  A2.received (a.getd ()); }}///:~

The syntax for nesting an interface within a class are reasonably obvious, and just like non-nested interfaces, these can H Ave Public or package-access visibility. can also see this both public and package-access nested interfaces can is implemented as public , pack Age-access, and private nested classes.

As a new twist, interfaces can also be  private , as seen in  A.D   (The S AME qualification syntax is used for nested interfaces as for nested classes). What good is a  private  nested interface? You might guess that it can is only implemented as a  Private  inner class as in  DIm P , but  a.dimp2  shows that it can also be implemented as a  public  class. however,  a.dimp2  can only be used as itself. You aren't allowed to mention the fact that it implements THE  private  interface, so Implementi ng a  Private  interface is a-a-to-force the definition of the methods in that interface Withou T adding any type information (that's, without allowing any upcasting).

The method  getd ( )  produces A further quandary concerning the  Private  interface:it ' s a  public  method, returns a reference to a < Strong>private  interface. What can I do with the return value of this method? in  Main ( ) , you can see several attempts to use the return value, and all of the which fail. The only thing that works are if the return value is handed to a object that have permission to use it-in this case, anothe r  A , via the  ReceiveD ( )  method.

Interface E shows that interfaces can is nested within each other. However, the rules about interfaces-in particular, which all interface elements must is public-are Strictly ENFORC Ed here, so an interface nested within another interface are automatically public and cannot be made private .

nestinginterfaces shows the various ways that nested interfaces can be implemented. In particular, notice if you implement a interface, you aren't required to implement any interfaces nested within . Also, Private interfaces cannot be implemented outside of their defining classes.

Initially, these features may seem like they is added strictly for syntactic consistency, but I generally find that once You know about a feature, and you often discover places where it is useful.

StackOverflow

The static keyword in the above example is redundant (a nested interface are automatically "static") and can be removed wit H no effect on semantics; I would recommend it be removed. The same goes for ' public ' on interface methods and ' public final ' on interface fields-the modifiers is redundant and J UST add clutter to the source code.

Either, the developer is simply declaring an interface named Foo.bar. There is no further association with the enclosing class, except that code which cannot access Foo would not being able to acc ESS Foo.bar either. (from source Code-bytecode or reflection can access foo.bar even if Foo is package-private!)

It's acceptable style to create a nested interface this-if you expect it-be-used only from the outer class, so tha t do not create a new top-level name. For example:

 public  class   Foo { public  interface   Bar { void   callback ();  public  static  void   RegisterCallback (bar bar) {...}}  //  Foo.registercallback (new   Foo.bar () { Span style= "color: #0000ff;" >public   callback () {...}});  

Learning of the internal interface of Java syntax--what is Inner Interface in Java?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.