Java Internal classes

Source: Internet
Author: User

To see a few words:

For non-static inner classes, you cannot have static members, such as variables, methods, and so on.

A non-static member of a static inner class can access a static variable of an external class, but not a non-static variable of the outer class.

Non-static members of non-static inner classes can access non-static variables of the outer class.

Java Internal class summary

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. Internal class member inner class, that is, as a member of an external class, you can directly use all members and methods of the external 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 class Outer {public         static void Main (string[] args) {             Outer Outer = new Outer ();             Outer.Inner Inner = Outer.new Inner ();             Inner.print ("Outer.new");                  Inner = Outer.getinner ();             Inner.print ("Outer.get");         }              It is recommended to use GETXXX () to get a member inner class, especially if the constructor of the inner class has no arguments, public         Inner Getinner () {             return new Inner ();         }              public class Inner {public             void print (String str) {                 System.out.println (str);             }         }     

  

2. Local inner class local inner class, refers to the inner class definition within the method and scope. Thinking in Java gives so two examples: defined within a method:
    public class Parcel4 {public         Destination Destination (String s) {             class Pdestination implements Destination {
   
    private String label;                      Private Pdestination (String whereto) {                     label = Whereto;                 }                      Public String Readlabel () {                     return label;                 }             }             return new Pdestination (s);         }              public static void Main (string[] args) {             Parcel4 p = new Parcel4 ();             Destination d = p.destination ("Tasmania");         }     
   

  

Defined in scope:
    public class Parcel5 {         private void internaltracking (Boolean b) {             if (b) {                 class Trackingslip {                     private St Ring ID;                     Trackingslip (String s) {                         id = s;                     }                     String Getslip () {                         return ID;                     }                 }                 Trackingslip ts = new Trackingslip ("slip");                 String s = ts.getslip ();             }         }              public void Track () {             internaltracking (true);         }              public static void Main (string[] args) {             Parcel5 p = new Parcel5 ();             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. Nested inner class nested inner classes, is the inner class 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 class Sometimes I prefer to use an anonymous inner class to avoid naming the inner class because it has no name. For example:
(Button) Findviewbyid (R.id.start)). Setonclicklistener (New Button.onclicklistener () {     @Override public     void OnClick (View v) {         new Thread () {              @Override public             void Run () {                 //TODO auto-generated method stub
   
    }          }.start ();     } });
   

  

Anonymous inner classes are not accessible modifiers. It is important to note that the new anonymous class, this class is to be defined first, see the following example:
    public class Outer {public         static void Main (string[] args) {             Outer Outer = new Outer ();             Inner Inner = Outer.getinner ("Inner", "GZ");             System.out.println (Inner.getname ());         }              Public Inner Getinner (final string name, String city) {             return new Inner () {                 private String nameStr = name;                      Public String GetName () {                     return nameStr;                 }             };         }     }          After commenting, the compile-time prompt class Inner cannot find     /* interface Inner {         String getName ();     

  

Also in this example, note the formal parameters of the methods of the outer class, The parameter must be final when the formal parameter of the method is used 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? On the internet to find himself more like the interpretation of:  "This is a compiler design problem, if you understand the Java compiler principle is easy to understand."   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.   This makes it easy to understand why you should use final, because both look the same thing from the outside, actually not, and if the internal classes get rid of the values of these parameters, it is not possible to affect the original parameters, but this loses the consistency of the parameters, because from the programmer's point of view they areThe same thing, if the programmer in the program design in the internal class to break the value of the parameter, but the external call and found that the value has not been removed, which makes it very difficult to understand and accept, in order to avoid this embarrassing problem exists, so the compiler designer to use the internal class can be used to set the parameters must 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 class Outer {public         static void Main (string[] args) {             Outer Outer = new Outer ();             Inner Inner = Outer.getinner ("Inner", "GZ");             System.out.println (Inner.getname ());         }              Public Inner Getinner (final string name, String city) {             return new Inner (name, city) {                 private String nameStr = NA Me;                      Public String GetName () {                     return nameStr;                 }             };         }     }          Abstract class Inner {         Inner (string name, String city) {             System.out.println (city);         }              Abstract String 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.         While anonymous inner classes are initialized with an instance, you can achieve the same effect as a constructor:
    public class Outer {public static void main (string[] args) {Outer Outer = new Outer ();             Inner Inner = Outer.getinner ("Inner", "GZ");             System.out.println (Inner.getname ());         System.out.println (Inner.getprovince ());                 Inner Getinner (final string name, final string city) {return new Inner () {                 Private String nameStr = name;                      Private String Province;                     Instance initialization {if (City.equals ("GZ")) {province = "GD";                     }else {province = "";                 }} public String GetName () {return nameStr;                 } public String Getprovince () {return province;         }             }; }} interface Inner {String gEtname ();     String getprovince ();  }

  

5. Inheritance of internal classes of inner classes, refers to internal classes are inherited, ordinary class extents inner class. And this time the code to be a bit special to deal with, specifically, see the following examples:
    public class Inheritinner extends Withinner.inner {              //Inheritinner () is not compiled, be sure to add formal parameter         Inheritinner (withinner WI) {             wi.super ();         }              public static void Main (string[] args) {             Withinner wi = new Withinner ();             Inheritinner obj = new Inheritinner (WI);         }     }          Class Withinner {         class Inner {              }     

  

You can see the constructor of the subclass to use the 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. Attach another article: "Doubts" appreciate the "inside" of the Java inner class to understand how the internal classes are handled at compile time.

Java Internal classes

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.