Deep understanding of the class within Java

Source: Internet
Author: User
Tags modifier

1. Why use inner classes if they are classes that are defined inside a class? The main reasons are as follows: First, the methods defined in the inner class can access the private properties and methods of the outer class; second, the outer classes cannot implement hiding other classes in the same package, and the inner classes can do this; thirdly, anonymous inner classes can effectively reduce our code volume when we simply use instances of the class in turn. For the above three points, we will cite specific examples below for further clarification. 2. How to use internal classes (1) using the inner class to access the outer class private variablesIn the inner class, we have access to the private instance variables and methods in its outer classes, see the following code:
1  Public classOuter {2     Private intown = 1;3      Public voidOutermethod () {4System.out.println ("In Outer class"); 5Inner Inner =NewInner ();6 Inner.innermethod ();7     }8      Public Static voidMain (string[] args) {9Outer Outer =NewOuter ();Ten Outer.outermethod (); One     } A      -     Private classInner { -          Public voidInnermethod () { theSystem.out.println ("The Var own in Outer is" +own); -         } -     } -}

The output of this code is as follows: we can see that the private variable own of the external class outer is actually accessed in the inner class. So, how does this work? In fact, an inner class object implicitly holds a reference to an external class object, and we assume that the reference is named outer, so the Innermethod method of the inner class is actually the same:
1  Public void Innermethod () {2     System.out.println ("The Var own in Outer is" + <strong>outer</strong>own); 3 }

The compiler modifies the constructor of the inner class, adding a reference to the external class outer as a parameter, presumably like this:
1  Public Inner (Outer Outer) {2     this. Outer = outer; 3 }

So we call the inner constructor in the Outermethod method of the outer class, and that statement will actually be "changed" by the compiler:
1 New Inner (this);


Let's take a look at the generated bytecode by JAVAP and feel it intuitively: let's take a look at this line: we can see that when we call the constructor of the inner class, we do pass in a parameter of type outer (that is, a reference to the perimeter class). We can also see that the compiler has generated a static method named access$100 for this class, in which the own variable is loaded and fetched.    In fact, the inner class calls this method to get the private instance variable own of the outer class. Let's take a look at the bytecode generated by the compiler for the inner class: Let's take a look at the lines of labels 16 and 19, we do now get the perimeter class reference, then call the Access$100 method, and pass in the perimeter class reference as the parameter, so that the private variables in the perimeter class can be accessed in the inner class. (2) special grammatical rules for inner classesIn fact, the formal syntax rules that use the perimeter class reference are as follows:
1 Outerclass.  This

For example, the Innermethod method of the above inner class we use the normal syntax should be written like this:
 Public void Innermethod () {    System.out.println ("The Var own in Outer is" + Outer.  this. own);}   
On the other hand, I can also use the following syntax to more explicitly initialize the inner class:
this. New Inner ();

We can also show that the outer class reference held by the inner class points to other peripheral class objects, assuming that Outerobject is an instance of the outer class, we can write:
Outerobject. New Inner ();

In this way, the perimeter class object reference that inner holds is outerobject. Outside the scope of the perimeter class, we can also refer to its inner class as follows:
Outerclass.innerclass


(3) Local inner classHaving an inner class is a class defined within a method, as shown in the following code:
1  Public classOuter {2     Private intown = 1;3      Public voidOutermethod () {4         classInner {5              Public voidInnermethod () {6System.out.println ("The Var own in Outer is" +own);7             }8         }9System.out.println ("In Outer class"); TenInner Inner =NewInner (); One Inner.innermethod (); A     } -      Public Static voidMain (string[] args) { -Outer Outer =NewOuter (); the Outer.outermethod (); -     } -}
The scope of a local class is limited to the method body of the method that defines it, so it cannot be decorated with public or private access modifiers. Compared to regular inner classes, local classes have an advantage: local variables can be accessed. However, there is a limitation that the local variables it accesses must be declared final. To put it simply, this is due to consistent considerations. Because the life cycle of a local variable ends with the end of the method's run, the life cycle of the local class does not end with the end of the method.    After the method has finished running, local classes need to be backed up in order to continue accessing local variables. In fact, when you create an object of a partial class, the compiler implicitly modifies the constructor that has the class, and passes the "external variable" to which it is being accessed as a parameter, so that the class can create a copy inside it and store it in its own instance domain. Imagine that if this variable is not final, that is, we can modify it in the class that we have, which will undoubtedly break the consistency of the data (the local variable is not the same as the copy version inside the local class). So the variable that you want the local class to access must have the final modifier. (4) Anonymous inner classFor classes that only need to be instantiated once, we can not give it a name, but instead use it in the form of an anonymous inner class. The syntax of an anonymous inner class is as follows:
New  supertype(construction parameters) {    class   methods and Data}

An anonymous class cannot have a constructor, so it passes the constructor argument to the superclass's constructor (supertype).    You can define methods and properties inside an anonymous class. There is also a form of anonymous inner class that implements some kind of interface, which has the following syntax format:
New  Interface() {    methods and Data}

Note that the meaning of the above code is not to instantiate an interface, but to instantiate an anonymous inner class that implements some kind of interface. One of the arguments we mentioned above for the constructor passed to time is a class object that implements the ActionListener interface, and obviously that class only needs to be instantiated once, so we can instantiate it with an anonymous inner class:
New ActionListener () {    publicvoid  actionperformed (ActionEvent event) {        ...    }}; 
(5) Static inner classSometimes, we don't want an inner class to hold a reference to the Outer class object, which is where we can choose to use the static inner class.    Static inner classes do not hold references to peripheral classes, and non-static inner classes hold references to peripheral objects (implicitly held), which is one of the common causes of memory Leak. Take a look at the following code:
1  Public classOuter {2     Private intown = 1;3      Public voidOutermethod () {}4      Public Static voidMain (string[] args) {}5     6     Private classInner {7          Public voidInnermethod () {}8     }9}

Now that the inner class inner is non-static, we use JAVAP to view the corresponding class file generated by the compiler:

As you can see, the inner class holds a reference to a outer class inside.     Now let's add the static modifier to the inner class to make it a statically internal class, and look at this: you can see that the inner class no longer holds references to the perimeter class outer. 3. Reference Java Core Technology (Volume 1) (watercress)

Deep understanding of the class within Java

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.