Java programming thought reading notes within class

Source: Internet
Author: User

Now is enough lazy, holiday time want to write this note, has been dragged to the present, recently read the "Java programming thought", I would like to do more than this note, because before the interview will always ask some internal class problems, the book's Notes from the internal class began to say.

I. Why internal classes are required

1. An object of an inner class can access private data for its perimeter class.

2. For other classes in the same package, inner classes can be hidden.

3. Use inner classes to implement multiple inheritance.

Two. Important summary of internal classes

1. Internal classes of scopes inside a method or inside a method

Eg: inner class inside the method

 Public Interface innerinterface {    string getStr1 (string xxx);}
 Public classOuter {Privateinnerinterface getstr () {classInnerImplementsinnerinterface {String sss= ""; @Override Publicstring getStr1 (string xxx) {sss=xxx; returnSSS; }} Inner Inner=NewInner (); returninner; }     Public Static voidMain (string[] args) {innerinterface innerinterface=NewOuter (). GETSTR (); System.out.println (INNERINTERFACE.GETSTR1 ("1234")); }}

Inner classes of the EG method scope

 Public Interface inface {    void  sysout ();}
 Public classOuter {inface getinface (Booleanflag) {        if(flag) {classInnerImplementsinface{@Override Public voidSysout () {System.out.println ("876"); }} Inner Inner=NewInner (); returninner; } Else {            classInnerImplementsInface {@Override Public voidSysout () {System.out.println ("123"); }} Inner Inner=NewInner (); returninner; }    }     Public Static voidMain (string[] args) {Outer Outer=NewOuter (); Inface Inface= Outer.getinface (true);        Inface.sysout (); Inface= Outer.getinface (false);    Inface.sysout (); }}

2. Anonymous inner class.

Anonymous inner classes can only be used once, primarily to simplify code

However, there is a precondition for using an anonymous inner class: An inner class must inherit a parent class or implement an interface

Eg: Demo to implement Interface

 Public classOuter {PrivateString str = "123";  Public Interfaceinnercalss{String value (String xxx); }     PublicINNERCALSS Getinnercalss () {return NewInnercalss () {PrivateString i;  Publicstring value (String xxx) {i=xxx; returni;    }        }; }     Public Static voidMain (string[] args) {Outer Outer=NewOuter (); System.out.println (OUTER.GETINNERCALSS (). Value ("12345")); }}

Eg: the demo that inherits the parent class

 Public classOuter { Public Abstract classInnerinterface {Abstractstring getStr1 (string xxx); }    Privateinnerinterface getstr () {return NewInnerinterface () {PrivateString sss = ""; @Override Publicstring getStr1 (string xxx) {sss=xxx; returnSSS;    }        }; }     Public Static voidMain (string[] args) {innerinterface innerinterface=NewOuter (). GETSTR (); System.out.println (INNERINTERFACE.GETSTR1 ("1234")); }}

Look at this implementation of anonymous inner class is not very common in the following code may know that the original has been writing anonymous internal classes, but not aware of it

 public  class   Threadinnerclass { public  static  void   main (string[] args) {Thread T = new   Thread () { public  void   run () {SYSTEM.OUT.P            Rintln ( "1234567" );        }        };    T.start (); }}
 Public class Runnableinnerclass {    publicstaticvoid  main (string[] args) {         New Runnable () {            publicvoid  run () {                    System.out.print ("1234567") );            }        };         New Thread (r);        T.start ();    }}
In addition, anonymous internal class parameters must be final type, where the demo is borrowed from the book
 Public classParcel10 { PublicDestination Destination (FinalString dest,Final floatPrice ) {    return NewDestination () {Private intCost ; //Instance initialization for each object:{ Cost=Math.Round (price); if(Cost > 100) System.out.println ("Over budget!"); }      PrivateString label =dest;  PublicString Readlabel () {returnlabel;}  }; }       Public Static voidMain (string[] args) {PARCEL10 P=NewParcel10 (); Destination D= P.destination ("Tasmania", 101.395F); }} /*Output:over budget!*///:~

3. Nested classes

Nested classes are mainly two types of

(1) Nested classes use static to modify internal classes or interface inner classes

Eg: here is a quote from the demo in the book

 Public classParcel11 {Private Static classParcelcontentsImplementsContents {Private inti = 11;  Public intValue () {returni;} }  protected Static classparceldestinationImplementsDestination {PrivateString label; Privateparceldestination (String whereto) {label=Whereto; }     PublicString Readlabel () {returnlabel;} //Nested classes can contain other static elements:     Public Static voidf () {}Static intx = 10; Static classAnotherlevel { Public Static voidf () {}Static intx = 10; }  }   Public StaticDestination Destination (String s) {return NewParceldestination (s); }   Public StaticContents Contents () {return Newparcelcontents (); }   Public Static voidMain (string[] args) {Contents C=contents (); Destination D= Destination ("Tasmania"); }}
 Public Interface classininterface {  void  howdy ();   class Implements Classininterface {    publicvoid  howdy () {      System.out.println ( "Howdy!" );    }      Public Static void Main (string[] args) {      new  Test (). Howdy ();}}  }

This is summed up in the inner class, as these are seldom used, take notes, and act as a memo.

Reference Document: "Java Programming Ideas", fourth edition

Java programming thought reading notes within class

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.