An inner class is a class that is redefined inside an outer class. The class name does not need to be the same as the folder. * Inner classes can be static, or public,default,protected and private adornments are available. (The external top-level class, which is the same as the class name and the file name, can only use public and default).Note: An inner class is a compile-time concept that, once compiled successfully, becomes a completely different class. For an external class named Outer and its internally defined inner class named inner. There are two classes of Outer.class and Outer$inner.class after the compilation is complete. Therefore, the member variable/method name of the inner class can be the same as the outer class. 1. member Inner classThe member inner class, which is a member of an external class, can directly use all members and methods of the outer class, even if it is private. While the outer class accesses all member variables/methods of the inner class, it needs to be fetched through the object of the inner class. It is important to note that the member inner class cannot contain static variables and methods.because the member inner class needs to create an external class before it can create its ownTo understand this, you can understand more and omit more details here. When a member's inner class is referencing an external class object, Outer.this is used to represent the outer class object, and the inner class object needs to be created, using outer.inner obj = outerobj.new inner ();
Public classOuter { Public Static voidMain (string[] args) {Outer Outer=NewOuter (); Outer.Inner Inner= Outer.NewInner (); Inner.print ("Outer.new"); Inner=Outer.getinner (); Inner.print ("Outer.get"); } //Personal recommendation Use GetXXX () to get a member inner class, especially if the constructor of the inner class has no arguments PublicInner Getinner () {return NewInner (); } Public classInner { Public voidprint (String str) {System.out.println (str); } } }
2. Local inner class
A local inner class, which refers to an inner class definition within a method and scope.
Defined within a method:
Public classParcel4 { PublicDestination Destination (String s) {classPdestinationImplementsDestination {PrivateString label; Privatepdestination (String whereto) {label=Whereto; } PublicString Readlabel () {returnlabel; } } return NewPdestination (s); } Public Static voidMain (string[] args) {Parcel4 P=NewParcel4 (); Destination D= P.destination ("Tasmania"); } }
Defined in scope:
Public classParcel5 {Private voidInternaltracking (Booleanb) {if(b) {classTrackingslip {PrivateString ID; Trackingslip (String s) {ID=s; } String Getslip () {returnID; }} trackingslip TS=NewTrackingslip ("Slip"); String s=Ts.getslip (); } } Public voidTrack () {internaltracking (true); } Public Static voidMain (string[] args) {Parcel5 P=NewParcel5 (); P.track (); } }
Local inner classes are compiled just like other classes, but only in different scopes, only within the scope of the method or condition, and cannot be referenced after exiting these scopes.
3. Nesting Inner classesNested inner classes are the inner class that is decorated as static. An inner class declared as static does not require a connection between an inner class object and an external class object, which means that we can refer directly to Outer.Inner, which means that you do not need to create an external class or create an inner class.There is another difference between nested classes and ordinary inner classes: ordinary inner classes cannot have static data and static properties, and cannot contain nested classes, but nested classes can. Nested classes cannot be declared private, and are generally declared public for easy invocation. 4. Anonymous inner classSometimes I prefer to use an anonymous inner class to avoid naming the inner class, because it has no name. For example: (Android Settings Click event)
(Button) Findviewbyid (R.id.start)). Setonclicklistener (new Button.onclicklistener () { @Override Public void OnClick (View v) { new Thread () { @Override publicvoid Run () { // } }.start ();} });
Anonymous inner classes are not accessible modifiers. Note that the new anonymous class, this class is to be defined first , see the following example:
Public classOuter { Public Static voidMain (string[] args) {Outer Outer=NewOuter (); Inner Inner= Outer.getinner ("Inner", "GZ"); System.out.println (Inner.getname ()); } PublicInner Getinner (Finalstring name, String city) { return NewInner () {PrivateString nameStr =name; PublicString GetName () {returnnameStr; } }; } } //note, the compile-time prompt class Inner cannot be found /*interface Inner {String getName (); } */ Also in this example, note the formal parameters of the methods of the outer class, when the formal parameter of the method in which it is used is required to be inside the inner class. You can see that the parameter name is already defined as final, and the formal parameter city is not used without being defined as final. Why should it be defined as final? Find yourself on the Internet more like the explanation: "This is a compiler design problem and it's easy to understand if you understand how Java is compiled. First, when the inner class is compiled, it generates a separate inner class of the. class file, which is not in the same class file as the external class. When an external class is called by an inner class, it is called directly from the Java program's point of view, for example: public void Dosome (final String a,final int b) { Class Dosome{public void Dosome () {System.out.println (a+b)}}; dosome some=new dosome (); some.dosome (); } from the code it seems that the internal class directly calls the A and B parameters, but actually not, after the Java compiler compiles the actual operation code is class outer$dosome{ Public Dosome (final String a,final int b) { this. Dosome$a=a; this. Dosome$b=b; } public void Dosome () { system.out.println (this). Dosome$a+this. DOSOME$B); } } from the above code, the inner class is not the parameter that calls the method directly, but the inner class backs up the passed-in arguments through its own constructor to the inside, and its own internal method call is actually its own property rather than the parameters of the external class method. So it's easy to understand why you want to use final, because the two look the same thing from the outside, actually not, if the internal classes get rid of the values of these parameters can not affect the original parameters, but this has lost the parameter consistency, Because from the programmer's point of view they are the same thing, if the programmer in the design of the internal class to break the value of the parameter, but the external call and found that the value has not been broken, which makes it very difficult to understand and accept, in order to avoid this awkward questionThe compiler designer sets the parameters that the internal class can use to be final to avoid the existence of this inexplicable error. ”(A simple understanding is that copy references, in order to avoid changes in the reference value, such as by the external class method modification, etc., resulting in the internal class resulting in inconsistent values, so the final to make the reference immutable)
Because anonymous inner class, no name, is with the default constructor, no parameters, if you need parameters? You need this class with a constructor with parameters:
Public classOuter { Public Static voidMain (string[] args) {Outer Outer=NewOuter (); Inner Inner= Outer.getinner ("Inner", "GZ"); System.out.println (Inner.getname ()); } PublicInner Getinner (Finalstring name, String city) { return NewInner (name, city) {PrivateString nameStr =name; PublicString GetName () {returnnameStr; } }; } } Abstract classInner {Inner (string name, String city) {System.out.println (city); } AbstractString getName (); }
Note here that the formal parameter city, because it is not used directly by the anonymous inner class, is used by the constructor of the abstract class inner, so it does not have to be defined as final.
The anonymous inner class can achieve the same effect as the constructor by initializing the instance:
Public classOuter { Public Static voidMain (string[] args) {Outer Outer=NewOuter (); Inner Inner= Outer.getinner ("Inner", "GZ"); System.out.println (Inner.getname ()); System.out.println (Inner.getprovince ()); } PublicInner Getinner (FinalString name,FinalString City) { return NewInner () {PrivateString nameStr =name; PrivateString Province; //Instance Initialization { if(City.equals ("GZ") ) {province= "GD"; }Else{province= ""; } } PublicString GetName () {returnnameStr; } PublicString getprovince () {returnProvince; } }; } } InterfaceInner {String getName (); String getprovince (); }
5. Inheritance of inner classesThe inheritance of the inner class refers to the inner class being inherited, the ordinary class extents inner class. And this time the code to be a bit special to deal with, specifically, see the following examples:
Public classInheritinnerextendsWithinner.inner {//Inheritinner () is not compiled, be sure to add a formal parameterInheritinner (Withinner wi) {wi.Super(); } Public Static voidMain (string[] args) {Withinner wi=NewWithinner (); Inheritinner obj=NewInheritinner (WI); } } classWithinner {classInner {}}
You can see the constructor of the subclass to usethe outer class object of the parent class. Super (), and this object needs to be created from the outside and passed to the formal parameter. As for the overload of the inner class, it is very complicated to feel thinking in Java, and it should be seldom in the ordinary application, because it is a bit difficult to understand and unclear. and the inner class and the closure between the things, temporarily put down, look later.
Summary of usage of Java internal classes