How to use a summary parameter for a Java inner class why use final

Source: Internet
Author: User
Tags class definition

A class is defined in the interior of 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 a member's inner class needs to create an external class before it can create its own, knowing 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 String 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. 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 {     
At the same time in this example,Note the formal parameter of the method of the outer class, which must be final when the formal parameter of the method is to be 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 explanation: "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 looks like the A and B parameters that are called directly from the inner class, 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 directly called by the method to pass in the parameters, but the internal class will pass in the parameters through their own constructor back to their own internal, the internal method calls the actual property of its own 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 embarrassing problem exists, So the compiler designer sets the parameters that internal classes can use to be final to avoid the existence of this inexplicable error. "  (simple to understand is that copy references, in order to avoid changes in reference values, 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);     }      
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 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 stri             ng 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 that the subclass's constructor uses the outer class object of the parent class. Super (); 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.

How to use a summary parameter for a Java inner class why use final

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.