Thinking in Java---inner class and an iterator instance

Source: Internet
Author: User

You can place the definition of one class inside the definition of another class, which is the inner class.
The definition of an inner class is simple, but its syntax is really complex and not very well understood. The following is a summary of the inner class.
I. Classification of internal classes
In general, internal classes are divided into ordinary inner classes, anonymous inner classes, local inner classes, nested classes (static inner classes), and so on. The following is a brief introduction to the syntax of these inner class definitions.
(1). For a normal inner class, the definition of another class is inserted in the perimeter class. As in the following code:

Package lkl1;///   Package a package class Public classParcel {///   Another class defined inside a class, called an inner class    ///   Its definition form is not different     Public classdestination{PrivateString label;        Destination (String whereto) {label=whereto; } PublicStringGetlabel(){returnLabel }    } Public classcontents{Private intI= One; Public int value(){returnI }    }///   provide a unified interface for creating internal classes     PublicDestinationDestination(String s) {return NewDestination (s); } PublicContentsContents(){return NewContents (); } Public void  Ship(String dest) {//You can actually call the constructor definition directly        //contents c1 = new Contents ();Contents C = Contents ();        Destination d = Destination (dest); System. out. println (D.label); } Public Static void Main(string[] args) {Parcel p =NewParcel (); P.ship ("Changsha"); Parcel p1=NewParcel ();///   define references for inner classes, note the hierarchy of names        ///define the alignment of the   inner class in a non-static method to specify the type of the object        //  outerclassname.innerclassnameParcel.contents c =p1.contents (); System. out. println (C.I.); Parcel.destination d = p1.destination ("Wuhan"); }}

(2). The so-called anonymous inner class has a peculiar syntax. The anonymous inner class does not have a name, so we cannot call the constructor to get its object as the general class does, and in general we put it in a method, which is responsible for returning an object of this anonymous inner class. Because the anonymous inner class has no name, So it is not possible to initialize through constructors, we can achieve the effect of constructors by initializing blocks (we can, of course, call the constructor of the base class to initialize the member variables of the base class). As in the following code:

Package lkl1; Public classPARCEL3 {////   for anonymous internal class variable initialization parameters must be final decorated    //destination is a class defined earlier.     PublicDestinationDestination(String dest,finalDoublePriceinti) {///   Create a generic format for anonymous inner classes        return NewDestination (i) { ////You can initialize the base class by calling the constructor of the base class            Private intCost {///   to initialize a constructor-like initialization process with an initialization blockCost = (int) Math.Round (price);if(cost> -) {System. out. println ("Over budget!"); }            }PrivateString label=dest; PublicStringReadlabel(){returnLabel    }        }; } Public Static void Main(string[] args) {Parcel3 p3=NewParcel3 (); Destination d = p3.destination ("Changsha",109.234,Ten); System. out. println (D.readlabel ()); }}

(3) The so-called local inner class is actually the inner class defined within the method and scope. This inner class is only valid within a certain range (in fact, the inner class is a local inner class). Generally we use it as a tool and do not want it to be publicly visible. As in the following code:

Package lkl1; Public classTest {PrivatePrintidCreate(){///   an inner class is defined in a method in an external class for implementing an interface;          ///   and then return a reference to this inner class{///  Printid is an interface of the previous definitionClass Print implements printid{PrivateString ID; Public Print() {id="Longkaili"; } Public void Print() {System. out. println (ID); }               }return NewPrint (); }//attempted to access an internal class in an extraterritorial scope error            //(New Print ()). ID;} Public Static void Main(string[] args) {////The   following is an explanation although the inner class is defined in a scope class          ///   But on the outside you can still use the functionality it implementsTest ts =NewTest (); Ts.create (). print ();///The   object of this class is created in this class of methods, and its private interface is visible}}

(4). Nested classes actually declare the inner class as static. For ordinary inner classes it has to depend on an object of an external class, and the nested class is not needed, and we can think of it as a static variable. As in the following code:

 PackageLKL1;/// when the inner class is declared static, we treat it as a static member///The inner class is not bound to an object in the outer class at this time. Public  class Parcel1 {    Private Static   class parcel1contents extendsContents{          Private intI=1; Public int value(){returnI }    }protected Static  class parcel1destination extends Destination{        PrivateString label;Private parcel1destination(String Whereto)        {Label=whereto; } PublicStringReadlabel(){returnLabel }    }//We can create objects of nested classes through static methods of external classes     Public  StaticDestinationDestination(String s) {return NewParcel1destination (s); } Public StaticContentsContents(){return NewParcel1contents (); } Public Static void Main(string[] args)        {Contents c= Contents (); Destination D =destination ("Changsha"); }}

Two. Relations between the external class and the inner class.
Since the inner class is defined inside the outer class, then there must be a certain connection. Specifically, we are divided into non-static generic inner classes and static modified nested classes for analysis.
(1). First, for the general inner class, its relation to the outer class is very close. Objects embodied in an inner class must be attached to an object of an outer class, i.e. we must pass an object of an outer class to create an object of the inner class. Second, all member variables of the outer class are visible to the inner class. The private member variable is included, and the external class can access all the variables of the inner class. In addition, the inner class can access its external class object explicitly through the. This method, and an external class can also create an object of the inner class through the. New method. Generally we are returning an object reference to an inner class through a method of an outer class. The following code demonstrates these points:

Package lkl1;///   test the external class for access to the inner class Public classOuter {Private intk= -;Private classinner{Private intI= -; Public intj=1111;Private void Print() {System. out. println ("OUTER.K ="+ k);///   internal class can access all member variables of an external classSystem. out. println ("Inner.print ()"); }  A variable of type static cannot be created in//non-static inner class       //Public   static int k=999;} Public void Print(Innerinch){///   The fact proves that the external class can access all the methods of the inner class as well, the variables        ///The   premise is that we have an inner class object that can be accessed directly through the class name .        inch. print ();inch. i++;inch. j + +; System. out. println (inch. i); System. out. println (inch. j); } Public Static void Main(string[] args) {Outer ot =NewOuter (); Outer.Innerinch= OT.NewInner ();////   through. New to create a reference to an inner class, notice how the inner class reference is declaredOt.print (inch); }}

(2). For nested classes with static adornments, the situation is different. With the example above we can see that the normal inner class object implicitly saves a reference to the perimeter object that created it. But for nested classes, its objects do not depend on objects of the outer class, Of course, it also cannot access non-static peripheral class objects. There is also a point. A static method cannot be included in a normal class, but it can be contained within a nested class. As shown in the following code:

 PackageLKL1;/// when the inner class is declared static, we treat it as a static member///The inner class is not bound to an object in the outer class at this time. Public  class Parcel1 {//contentshedestination are all abstract classes defined earlier    Private Static   class parcel1contents extendsContents{          Private Static intk= the;Private intI=1; Public int value(){returnI }    }//We can create objects of nested classes through static methods of external classes     Public StaticContentsContents(){return NewParcel1contents (); } Public Static void Main(string[] args) {/// access Parecel1 Static variables, note the call formatSystem.out.println ("static variable K of parcel1contents"+PARCEL1.PARCEL1CONTENTS.K);    Contents c= Contents (); }}

Three. The role of the inner class
The syntax of the inner classes is complex, but what confuses me when learning these complex grammars is: what is the use of inner classes? Java programming ideas The book says:
1. Each inner class can inherit itself from one (interface) implementation independently, so no matter whether the perimeter class has inherited an implementation of (an interface), there is no effect on the inner class.
2. Multiple inheritance can be better implemented. We know that the common class is not multiple inheritance, but now through the inner class, we can achieve the effect of multiple inheritance for the ordinary class.
3. There are important applications in some design patterns.
For these are not all can understand clearly, hope in the future study can be clear.
The following is an instance of implementing an iterator through an inner class. The following sequence class is a generic class that encapsulates an object array, and selector is a general-purpose iterator interface, and we implement the selector interface in sequence with an inner class. The sequence object is then iterated over through the interface of this inner class. In fact, we have been exposed to the iterator of the collection class.

 PackageLKL1;/// Define a common iterator interface Public  interface Selector {    BooleanEnd (); Object current ();voidNext ();} PackageLKL1;the///sequence class encapsulates a fixed-size///object An array, and then provides an iterator of its own///The nature of all the data that an inner class can access to an external class is exploited here Public  class Sequence {    Privateobject[] items;Private intnext=0;/// Keep the current number of elements     Public Sequence(intSize) {items=NewObject[size]; } Public void Add(Object obj) {if(next<items.length)        {items[next++]=obj; }    }/// encapsulates an internal class implementation iterator    Private  class sequenceselector implements Selector{        Private intI=0;/// number of current access to element         Public Boolean End(){returnI==items.length; } PublicObject Current(){returnItems[i]; } Public void Next(){if(i<items.length) i++; }    }/// provide external interface for iterators     PublicSelectorselector(){return NewSequenceselector (); } Public Static void Main(string[] args) {Sequence sq=NewSequence (Ten); for(intI=0;i<Ten; i++) Sq.add (integer.tostring (i));/// use an iterator from the sequence itself to accessSelector se =sq.selector (); while(!se.end ()) {System.out.print (se.current () +" ");        Se.next ();    } System.out.println (); }}

Thinking in Java---inner class and an iterator instance

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.