Rookie growth Diary: Java Foundation 8---inner class

Source: Internet
Author: User
Tags getmessage thread class

(i), the concept of internal classes
1, the internal class is a compile-time concept, once compiled successfully, it is with the peripheral class belongs to two completely different classes (of course they are still connected).
2. For a perimeter class named Outerclass and an inner class named Innerclass, after a successful compilation,
There will be two class files: Outerclass.class and Outerclass$innerclass.class.
3, the use of internal classes The greatest advantage is that it can be very good to solve the problem of multiple inheritance
4. The inner class provides a better encapsulation, except for the perimeter class, which cannot be accessed by other classes.

(ii) Classification of internal classes
Inner classes in Java are mainly divided into member inner class, local inner class, anonymous inner class, static inner class.

  first, the members of the internal class :
1. The member inner class is a member of the perimeter class, so he is allowed unrestricted access to all member properties and methods of the perimeter class
2, although private, the perimeter class to access the member properties and methods of the inner class is accessed through an internal class instance.
3, there can be no static variables and methods in the member's inner class;
4, the member inner class is dependent on the outer class, so only the perimeter class is created first to be able to create the inner class.

code example:

/*** Member internal class Test *@authorWangchong * @date October 23, 2017 PM 3:30:50*/ Public classouterclasstest1{ PublicString Outername;  PublicOuterClassTest1 (String outername) { This. Outername =Outername; }        /*** Get a reference to an inner class *@return     */     Publicinnerclass Getinnerclass () {return NewInnerclass (outername); }        /*** Internal class *@authorWangchong * @date October 23, 2017 PM 5:12:41*/    Private classinnerclass{PrivateString Innername; Privateinnerclass (String outername) { This. Innername =Outername; }                /*** Get External class *@return         */        PrivateOuterClassTest1 GetOuterClassTest1 () {returnOuterClassTest1. This; }            }             Public Static voidMain (string[] args) {OuterClassTest1 outerTest1=NewOuterClassTest1 ("Names"); //the first way to get an instance of an inner classOuterclasstest1.innerclass InnerTest1 =Outertest1.getinnerclass (); //The second wayOuterclasstest1.innerclass innerTest2 = OuterTest1.NewInnerclass (outertest1.outername); //the above two ways of comparison, obviously the first way betterSystem.out.println (Innertest1.getouterclasstest1 (). Outername+ "," +innertest1.innername); System.out.println (Innertest1.getouterclasstest1 (). Outername+ "," +innertest2.innername); }}


  second, the local inner class :
Nested within the method and scope, the use of this class is mainly to apply and solve more complex problems, want to create a class to assist our solution, then do not want this class is publicly available.
Therefore, a local inner class is generated, and the local inner class is compiled just like the inner class of the member, except that its scope has changed, it can only be used in the method and property, and the method and property will be invalidated.

code example:

/*** Local internal class testing *@authorWangchong * @date October 23, 2017 PM 5:13:31*/ Public classOuterClassTest2 { Public intLimitnum;  Public voidSetnum (intnum) {         This. Limitnum =num; }        //define the inner class within the scope     Public voidGetClass1 (intN) {        if(N >limitnum) {                        /*** Define the inner class in scope *@authorWangchong * @date October 23, 2017 PM 5:39:41*/            classInnerClass1 {//internal conditions                Private intInnernum;  PublicInnerClass1 (intinnernum) {                     This. Innernum =Innernum; }                                Private voidGetMessage (intN) {if(N <=innernum) {System.out.println ("Value passed outside condition, lower than internal condition"); }Else{System.out.println ("Value passed outside condition, above internal condition"); }}} InnerClass1 Innerclass=NewInnerClass1 (10);            Innerclass.getmessage (n); }    }        //defined in the method     Public intGETNUM2 (intnum) {        /*** Define the inner class within the method *@authorWangchong * @date October 23, 2017 PM 7:10:20*/        classInnerClass2extendsOuterClassTest2 { Public intLimitnum = (num + 1);  Public intGetlimitnum () {returnLimitnum; }        }                return(NewInnerClass2 ()). Getlimitnum (); }         Public Static voidMain (string[] args) {OuterClassTest2 Outerclass=NewOuterClassTest2 (); Outerclass.setnum (1); Outerclass.getclass1 (8); System.out.println (Outerclass.getnum2 (10)); }}


  Anonymous inner class: Anonymous inner class is also an inner class without a name
1, because there is no name, so anonymous internal class can only be used once, it is often used to simplify code writing
2, the use of anonymous inner class has a precondition: must inherit a parent class or implement an interface
3. If a class has a parent or parent interface and is used only once, the anonymous inner class can be used at this time

Code implementation:

/*** Anonymous Inner class *@authorWangchong * @date October 23, 2017 PM 7:23:27*/ Public classOuterClassTest3 { Public Static voidMain (string[] args)throwsinterruptedexception {//anonymous inner class implements runnable interfaceRunnable r =NewRunnable () { Public voidrun () { for(inti = 1; I <= 5; i++) {System.out.print (i+ " ");        }            }        }; Thread T=NewThread (R);                T.start (); Thread.Sleep ((Long) Math.random () *1000);                System.out.println (); //anonymous inner class inherits the thread classThread z =NewThread () { Public voidrun () { for(inti = 1; I <= 5; i++) {System.out.print (i+ " ");        }            }        };    Z.start (); }}


  static inner classes: internal classes that use static adornments, which we call static inner classes or nested inner classes.
1. A non-static inner class implicitly holds a reference after compilation, which points to the perimeter in which it was created, but the static inner class has no
2, the creation of static inner class is not necessary to rely on the outer class.
3. Static inner classes cannot use non-static member variables and methods of any perimeter class.

code example:

/*** Static Inner class *@authorWangchong * @date October 23, 2017 PM 7:33:35*/ Public classOuterClassTest4 {PrivateString ClassName;  PublicOuterClassTest4 (String className) { This. ClassName =ClassName; }    /*** Static Inner class *@authorWangchong * @date October 23, 2017 PM 8:04:59*/     Public Static classInnerClass1 {Private StaticString name1; Private intAge ;  PublicInnerClass1 (String name,intAge ) {             This. name1 =name;  This. Age =Age ; }                 Public voidShowMessage () {//System.out.println ("Name:" + name2 + ", Age:" + ages + ", Grade:" + className); Compile error, cannot use external non-static properties and methodsSystem.out.println ("Name:" + name1 + ", Age:" +Age ); }    }        /*** Non-static inner class *@authorWangchong * @date October 23, 2017 PM 8:05:16*/     Public classInnerClass2 {PrivateString name2; Private intAge ;  PublicInnerClass2 (String name,intAge ) {             This. name2 =name;  This. Age =Age ; }                 Public voidShowMessage () {System.out.println ("Name:" + name2 + ", Age:" + ages + ", Grade:" +className); }            }         Public Static voidMain (string[] args) {OuterClassTest4 Outerclass=NewOuterClassTest4 ("Second class in third grade"); //creation of static inner classes does not depend on external classesInnerClass1 Inner1 =NewInnerClass1 ("Xiao Ming", 10); Outerclasstest4.innerclass2 Inner2= Outerclass.NewInnerClass2 ("Little Red", 9);        Inner1.showmessage ();            Inner2.showmessage (); }}

Rookie growth Diary: Java Foundation 8---inner 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.