JAVA nested classes and inner classes

Source: Internet
Author: User

What are nested classes and inner classes?
You can define another class within one class, which is called a nested class (nested classes), and it has two types:
Statically nested classes and non-static nested classes. Static nested classes use very little, and most importantly, non-static nested classes, which are called
Inner class (inner). Nested classes are introduced from JDK1.1. Among them, the inner class can be divided into three kinds:
One, the inner class directly defined in a class (outer class);
Second, the inner class defined in a method (the method of the outer class);
Its third, anonymous inner class.
Below, I will explain the use and considerations of these types of nested classes.
Second, Static nesting class
The code below defines a static nested class as follows.

 Public classMyTest {Private StaticString name = "Javajohn"; PrivateString id = "X001"; Static classperson{PrivateString address = "Swjtu,chendu,china";  PublicString mail = "[email protected]";//internal class public members         Public voiddisplay () {//System.out.println (ID);//non-static members of external classes cannot be accessed directlySYSTEM.OUT.PRINTLN (name);//only static members of external classes can be accessed directlySystem.out.println ("Inner" +address);//Access this internal class member.         }     }          Public voidPrintinfo () { person person=NewPerson ();         Person.display (); //System.out.println (mail);//not accessible//System.out.println (address);//not accessibleSystem.out.println (person.address);//can access private members of inner classesSystem.out.println (Person.mail);//access to the public members of the inner class    }          Public Static voidMain (string[] args) {MyTest statictest=NewMyTest ();     Statictest.printinfo (); } }

Inside a static nested class, you cannot access non-static members of an external class, which is qualified by the Java syntax in which static methods cannot access non-static members directly.
If you want to access the variables of an external class, it must be resolved by other means, and for this reason, there are few static nested classes. Note that the external class accesses the inside
The members of a class are somewhat special and cannot be accessed directly, but can be accessed through internal classes, because all members and methods within a static nest default to
Static. Also note that the internal static class person is only visible within the scope of the class statictest and is wrong if referenced or initialized in other classes.
Iii. defining inner classes in the outer class
The code below defines two inner classes and their invocation relationships in the outer class as follows:

 Public classMyTest {intouter_x = 100; classinner{ Public inty = 10; Private intz = 9; intm = 5;  Public voiddisplay () {System.out.println ("Display outer_x:" +outer_x); }         Private voidDisplay2 () {System.out.println ("Display outer_x:" +outer_x); }     }         voidTest () {Inner Inner=NewInner ();         Inner.display ();         Inner.display2 (); //System.out.println ("Inner y:" + y);//cannot access internal variables insideSystem.out.println ("Inner y:" + inner.y);//can accessSystem.out.println ("Inner z:" + inner.z);//can accessSystem.out.println ("Inner m:" + inner.m);//can accessInnertwo Innertwo =NewInnertwo ();     Innertwo.show (); }         classinnertwo{Inner Innerx=NewInner ();  Public voidShow () {//System.out.println (y);//cannot access y members of Innter//System.out.println (INNER.Y);//Do not directly access any members and methods of innerInnerx.display ();//can accessInnerx.display2 ();//can accessSystem.out.println (INNERX.Y);//can accessSystem.out.println (INNERX.Z);//can accessSystem.out.println (INNERX.M);//can access        }     }      Public Static voidMain (String args[]) {MyTest outer=NewMyTest ();     Outer.test (); } }

The above code needs to be explained, for the inner class, usually in the definition of the class keyword is not public or private, such as restrictions, if added
Without any effect, as if these qualifiers have no effect on the variables and methods of the inner class (?). In addition, it is important to note that the internal class inner and
Inntertwo is only known within the scope of the class outer, if any code outside of the class outer attempts to initialize the class inner or use it, the compilation does not
Will pass. At the same time, the variable members of the inner class are only visible inside internally, and if an external class or the same level of internal classes needs access, the sample program is used
, you cannot directly access the variables of the inner class.
Iv. defining an inner class in a method
The code below defines an inner class within the method as follows:

 Public classMyTest {intout_x = 100;  Public voidTest () {classinner{String x= "X"; voiddisplay () {System.out.println (out_x); }} Inner Inner=NewInner ();     Inner.display (); }          Public voidshowstr (String str) {//Public String str1 = "Test Inner";//not defined, only final decoration allowed//static String STR4 = "static Str";//not defined, only final decoration allowedString str2 = "Test Inner"; FinalString STR3 = "Final Str"; classinnertwo{ Public voidTestprint () {System.out.println (out_x);//variables with direct access to external classes//System.out.println (str);//non-final variables inside this method are not accessible//System.out.println (str2);//non-final variables inside this method are not accessibleSystem.out.println (STR3);//only the final variable members of this method can be accessed}} innertwo innertwo=NewInnertwo ();     Innertwo.testprint (); }          Public voidUse () {//Inner innerobj = new Inner ();//at this time inner was not visible. //System.out.println (inner.x);//at this time inner was not visible.     }          Public Static voidMain (string[] args) {MyTest outer=NewMyTest ();     Outer.test (); } }

From the above example, we can see that the inner class defined within the method is less visible, it is only inside the method
can be seen in external classes (and other methods of external classes). At the same time, it has a characteristic that is the method
The inner class within the method cannot access the member variables of the methods, it can only access the final members of this method. At the same time another
It is important to note that the method internally defines a member, which allows only final or no modifiers, and other things such as static are not available.
Five, anonymous internal class
The code below defines an anonymous inner class as follows: Anonymous inner classes are typically used in Java event handling

ImportJava.applet.Applet;ImportJava.awt.event.MouseAdapter;Importjava.awt.event.MouseEvent; Public classMyTestextendsapplet{ Public voidinit () {Addmouselistener (NewMouseadapter () { Public voidmousepressed (MouseEvent me) {showstatus ("Mouse pressed!");    }        }); }      Public voidshowstatus (String str) {System.out.println (str); } } 

In the example above, the method Addmouselistener accepts an object-type parameter expression, so in the argument we define an anonymous inner class, which is a class of mouseadapter type. At the same time, an inherited method mousepressed is defined in this class, and the entire class is used as a parameter. This class has no name, but it is automatically instantiated when the expression is executed. Also because, this anonymous inner class is defined inside the Anonymousinnerclassdemo class, so it can access its method showstatus. This is consistent with the previous inner class.
Vi. other problems in the use of internal classes
From the above, we can clearly see some of the use of internal classes, at the same time, in many cases, internal classes are in the case of Java event processing, or as a value object to use. At the same time, we need to pay attention to the last problem, that is, the internal similar to other classes are defined, as well as it can inherit the outer package of the class and implement the interface elsewhere outside. It can also inherit other inner classes of the same level, and can even inherit the outer class itself. Here we give the last example as the end:

 Public classMyTest {//member variables of the layer class    PrivateString teststr = "Teststr"; //Person class, base class    classPerson {String name;        email email;  Public voidsetName (String nameStr) { This. Name =nameStr; }         PublicString GetName () {return  This. Name; }         Public voidSetemail (Email emailobj) { This. email =Emailobj; }         PublicString Getemail () {return  This. EMAIL.GETMAILSTR (); }        //Inner class of inner class, multi-layer inner class        classEmail {String mailid;            String mailnetaddress; Email (String mailid, String mailnetaddress) { This. Mailid =Mailid;  This. mailnetaddress =mailnetaddress; } String Getmailstr () {return  This. mailid + "@" + This. mailnetaddress; }        }    }    //another inner class inherits the outer class itself    classChildlayerextendsMyTest {voidprint () {System.out.println (Super. teststr);//accessing the member variables of the parent class        }    }    //another inner class inherits an inner class person    classOfficepersonextendsPerson {voidShow () {System.out.println (name);        System.out.println (Getemail ()); }    }    //test methods for external classes     Public voidtestfunction () {//testing the first inner classChildlayer Childlayer =NewChildlayer ();        Childlayer.print (); //Testing the second inner classOfficeperson Officeperson =NewOfficeperson (); Officeperson.setname ("Abner Chai"); //Note here that you must use the object. New object's Subclass object//Instead of Person.new Email (...) //also not new Person.email (...)Officeperson. Setemail (Officeperson.NewEmail ("Josserchai", "yahoo.com"));    Officeperson.show (); }     Public Static voidMain (string[] args) {MyTest layer=NewMyTest ();    Layer.testfunction (); }}

Original: http://www.2cto.com/kf/201208/145048.html

JAVA nested classes and inner classes

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.