Java inner class and final keyword

Source: Internet
Author: User

First, several methods of creating internal classes:

1. member Inner class

Class outer{Private int i = 1;      Class inner{public          void Fun () {System.out.println ("Outer i=" + I)}          }      }  


2. Method Inner Class

Class outer{public  void Fun () {      final int i = 1;//local variables accessed by the method's inner class must be final decorated class    inner{//method inner class cannot have access modifiers, such as Public public        void print () {System.out.println ("Method i=" + I)}}}        


3. Anonymous inner class

Interface USB {public      abstract void Start ()      }  class outer{public      void Fun () {      final int i = 1; Local variables accessed by anonymous internal classes must be final decorated with    new USB () {  @Override public    void Start () {                      System.out.println ("Local _var_i= "+ i);                  }              }. Start ();          }      }  


4. Static internal class

Class outer{  private int i = 1;  Static class inner{//cannot access non-static members of external class public void Fun () {}        }  


5. Interface Inner class

Interface USB {      class Inner {////default is public static, which can be directly new USB. Inner ();    }  }  

Second, God Horse is the inner class?

At first glance, a lot of ways to create, it's quite complicated, right? First of all, what's an inner class?
Definition: Creates a type inside a class. They are divided into members, methods, and anonymous, depending on where they are created. An inner class in an interface is called an interface inner class.
Understanding: Created inside a class, that is part of a class, with attributes, methods, and peers. This also explains why you can access external private members, I am part of you, and I certainly have access to them.

The problem of the derivation < understanding of the internal class;

That's the problem, I'm a part of you, other people inherit the external class, will not also inherit the inner class also past it? This has to be explored from the original and object oriented design of the inner class.
For example, we use the body class to describe the human body. If it is a description of the human word, it will describe the nature and function of human beings.
Now we describe the human body, the human body heart liver spleen and stomach kidney, these re-use attributes to describe it is not appropriate? What about that? We can use the inner class to describe it.
So, whether the inner class is public or private, it is not inherited because he is not a property, nor is it a method. It's a description of an internal transaction, which we call an inner class.
Inner classes are better able to encapsulate internal transactions, see examples:

In the body class, there are various organs belonging to the body, each organ has its own function and properties, so we encapsulate it as an inner class to describe separately.
The inner class used to describe an organ is part of the body, so it is possible to freely access the resources (properties and functions) of the body, and the organs and bodies work in harmony with each other.

public class Body {  private class Heart {//Heart public void bloodsupply () {  //blood      supply ...  }       }  private class Hepar {//Liver public void metabolism () {  //metabolism ...      }       }  private class Spleen {//Spleen public void Storageblood () {  //stored blood ...           }        }  Private class Stomach {//Stomach public void Digest () {//  digest ...           }        }  Private class Kidney {//Kidney public void Dischargepoison () {  //Detox ...}}  }

The issue of the derivation < internal class access to the external class member mode;:

Because of the ability to access external private members, the problem was born, how did he access it?

1: For the member inner class, he holds a reference to the current object of the outer class, Outer.this.
This makes it possible to invoke methods that are visible to the outer class and to the member variables, which are invoked by holding the external class reference. Outer.this.fun ();
How do you get access to private members? is accessed by the static access$0 () method that is generated by the compiler in the external class. Outer.this.access$0 (Outer);




2: For the method inner class (anonymous inner Class), because the internal class to access the local variables in the method, this time with the external class holding the current object reference can also be called to?
Cannot be adjusted, the Java language designers are so to solve this problem: Copy Local variables to the internal class use, how to copy? The way in which values are passed by construction methods when the inner class is initialized.
In this way, the inner class will have a copy of the private decorated member variable. So I can have a visit. But here's the problem again, like:

public void Fun () {  int i = 1;  Class inner{  //int i = 1; generated by compiler publicvoid print () {i++}      }     System.out.println ("i=" + i);   Or will output i=1, we clearly in the internal class method of this variable is + + AH. Sorry, your + + is a copy of the other copies. }   

The problem leads < maintains the consistency of two different variables;


Well, the problem is so ruthless, how to solve? Java also said, otherwise add final to the local variables, so it will remain worthy of consistency.
OK, problem solved, that's why the local variables that the method internal class accesses must be final modified (in order to constrain the consistency of two different variables). Design problems, very helpless solution.


Take a look at another way of saying:
In Java, the local variables of the method are on the stack, and the object is on the heap.
Because the scope of the local variable is limited to the method, when a method ends, the stack structure is deleted and the variable disappears.
However, the inner class object defined in this class still survives on the heap, so the inner class object cannot use local variables. Unless these local variables are identified as final.


This argument is one-sided, because the underlying reason is that the internal class object cannot access the local variable before it replicates a copy.
To ensure consistency of two variables, the final keyword is used to modify the local variables. Not because the stack life cycle is inconsistent with the heap life cycle.

Third, finally, the final key words:

The object variable is decorated with the final keyword, except that the object reference is not allowed to point to other objects, but the contents of the object pointed to by this reference can be changed.
For example, a classic example:

Final StringBuffer sb = new StringBuffer ("HelloWorld");  SB = new StringBuffer ("Hello"); Compilation failed, cannot modify the point sb.append ("China") of SB-reference; The object that SB points to can be modified.


In fact, from the final position it is shown that he is in the modification of the reference type variable SB, not in the decorated heap instance object (new StringBuffer ("HelloWorld");)

Java inner class and final keyword

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.