Analysis of Java inner class

Source: Internet
Author: User

First, Introduction

Because currently is the development of Android interns, in the development process to find more and more know but really use the situation, such as the use of internal classes, so after the online search for information learning and their own summary, hereby publish a blog post with you to share, if there is inappropriate, million hope pointed out.

The inner class is defined as a class within an external class, is a compile-time concept, once compiled successfully, the inner class and its external classes will become a completely different two classes, but the inner class is preceded by the class name of the outer class and the $ symbol, such as a outer class inside defines a inner inner class , the Outer.class and Outer$inner.class two classes are generated when the compilation is complete, so the member variables and methods of the inner class can be the same as the external classes. From the definition of the inner class, in fact, the internal class seriously destroys the good code structure, then why use the inner class? This is the only advantage of an inner class because the inner class is free to use the member variables of the outer class (including private ones) without generating the outer class object. Iii. classification of inner classes and examples inner classes are divided into member inner classes, local inner classes, static inner classes, and anonymous inner classes. The following are described for each of the internal classes: (1) member Inner class

exists as a member of an external class, in parallel with the properties and methods of the outer class. All members of an external class can be accessed within a member's inner class, and an external class name is used when the variable name of the outer class is duplicated from the inner class. This variable name can be invoked on variables of the outer class and can be invoked directly using the variable name if there are no duplicates. Accessing a static inner class in a normal external class method can be used to create a new out-of-member class object and invoke the method directly in it, whereas in a static external class method It is necessary to first new class object, and then call the Outer classes object name. The method of the new inner class to get the member inner class object.

A static variable cannot be defined in a member's inner class, because the member inner class needs to create an external class before it can create its own.

A member inner class can use private members and properties of an external class, and it defines inaccessible properties in an external class, allowing access that is smaller than the private of the outer class in the outer class.

The sample code is as follows:

/** *  * @ClassName: Memberinnerclass * @Description: Member Inner class * @author ADAM * @date July 25, 2014 morning 9:20:28 * */public clas s Memberinnerclass {private int i = 0;public class Inner {//member Inner class can be added with permission modifier int i = 3;public void print () {System.out.println (i);//The output is an internal class I, the value is 3system.out.println (THIS.I),//output is an internal class of I, the value is 3system.out.println (MEMBERINNERCLASS.THIS.I);// Output the external class I with a value of 0}}public void print () {(New Inner ()). print ();//External class ordinary method call member inner class directly new out of inner class to call}public static void main (string[ ] args) {(new Memberinnerclass ()). New Inner ()). print ();//External class static method call member inner class first new outside class and then new out internal classes to call}}

(2) Local inner class

An inner class defined in a method, similar to a local variable, without a modifier public or private before a local inner class, whose scope is the block of code that defines it. A static variable cannot be defined in a local inner class, and a variable in an external class (that is, a method) can be accessed, but the variable must be final. When a local inner class is named with the outer class with the same name as the member's inner class, access to the local inner class must have an outer class object first.

Local inner classes cannot be generated directly outside the class (ensuring that local inner classes are not visible externally). To use a local inner class, you need to generate an external class object, and the object then calls the method in order to invoke its local inside. Through the internal class and interface to achieve a forced weak coupling, with the local inner class to implement the interface, and return the interface type in the method, so that the local inner class is not visible, masking the implementation of the visibility of the class.

The sample code is as follows:

/** *  * @ClassName: Localinnerclass  * @Description: Local inner class * @author ADAM * @date July 25, 2014 morning 10:36:26  * */pub  Lic class Localinnerclass {private int j = 3;private int i = 2;public void Test () {Memberinnerclass Memberinnerclass = new Memberinnerclass ();//To access members in other classes the inner class can only be used if the modifier of the member's inner class is public, or else the compilation error is That is, the member inner class can again implement the internal implementation of the lower than private permissions memberinnerclass.new Inner (); final int i = 0;class Inner {//Here must not be added with the private modifier, otherwise compilation error int i = 1;public void print () {System.out.println (j); modifier, otherwise compile error System.out.println (i);//output local inner Class I, The variables in the external method can only be called SYSTEM.OUT.PRINTLN (localinnerclass.this.i) in the form of a parameter, or//the output is i}}inner Inner = new Inner () in the external class;// A local inner class can only be instantiated within a method and called Inner.print ();} public static void Main (string[] args) {(new Localinnerclass ()). Test ();}}

A local inner class can be defined not only in a method but also within a scope. The following provides two thinking in Java 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");     } } <span style= "LINE-HEIGHT:1.3EM; font-family: ' Courier New ', monospace; Background-color:inherit; " > </span>
   

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, except that scopes are different and can only be used within the scope of the method or condition, and these scopes cannot be used.

(3) Static inner class

static inner classes, also known as nested inner class, are defined in a class, outside any method, with static definitions, statically or non-static members can be defined, and are decorated with public, private, and other modifiers, which are generally decorated with public, convenient to call, It can only access static members in the outer class. An external class accesses static members in a static inner class directly using an inner class. Static members, when accessing non-static members of a static inner class, instantiate the static inner class and then access through the object.

generating a static inner class does not require an external class object member, which is distinguished from the inner class of the member, while the ordinary inner class cannot have static methods and properties, nor can it contain nested classes, and the objects of the static inner class are directly generated: external classes. Inner Class object name = New External class. Inner Class () Can

Note: When a method naming conflict occurs between a class and an interface (or interface and interface), you must use an inner class to implement it. The interface does not fully implement multi-inheritance, with the interface with the inner class in order to achieve true multi-inheritance.

The sample code is as follows:

/** *  * @ClassName: Staticinnerclass  * @Description: Static inner class * @author ADAM * @date July 25, 2014 morning 10:37:04  * */PU  Blic class Staticinnerclass {private int i = 1;public static int j = 1;public int k = 0;public Static class Inner {private int i = 0;private static int j = 0;//can define static and non-static members public static void print () {//system.out.println (k);//Compile error, do not invoke non-static in external class Member System.out.println (new Staticinnerclass (). i);//accessing non-static member variables in an external class requires an instantiation of the System.out.println (j); System.out.println (New Staticinnerclass (). j);//static inner class uses static members in external classes}}public the statics void Main (string[] args) {Inner.print ();//An external class static method or a non-static method invokes a static member in a static inner class directly inside the class name. Member can staticinnerclass.inner Inner = new Staticinnerclass.inner ();// The instantiation of a static inner class does not require an instance of the System.out.println (INNER.I), or a static inner class must be instantiated first to access a non-static member in a static inner class}}

The example code for multiple inheritance through an inner class is as follows:

/** * * @ClassName: Pencil * @Description: Pen class * @author ADAM * @date July 25, 2014 morning 10:42:59 * */public abstract class Pe ncil {public abstract void write ();} /** * * @ClassName: Eraser * @Description: Eraser class * @author ADAM * @date July 25, 2014 morning 10:43:28 * */public abstract class Eraser {public abstract void erase ();}  /** * * @ClassName: Pencilwitheraser * @Description: Multiple Inheritance class * @author ADAM * @date July 25, 2014 Morning 10:43:53 * */public class Pencilwitheraser {private Mypencil pencil = new Mypencil ();p rivate myeraser eraser = new Myeraser ();p Rivate class Mypenci L extends Pencil {//Inherit pen class @overridepublic void Write () {System.out.println ("to write");}} Private class Myeraser extends Eraser {//Inherit eraser class @overridepublic void Erase () {System.out.println ("to Erase");}} This class own method, call the method in the inheriting class public void write () {pencil.write ();} public void Erase () {eraser.erase ();} public static void Main (string[] args) {Pencilwitheraser pencilwitheraser = new Pencilwitheraser (); Pencilwitheraser.write ();p encilwitheraser.erase ();}} 

(4) Anonymous inner class  For inheriting other classes or implementing interfaces, there is no need to add additional methods, just an override or implementation of an inherited method, and it is used only to get an object instance, without knowing its actual type, at which time the class name is meaningless and does not need to be used.
The sample code is as follows:

/** *  * @ClassName: Anonymousinnerclass  * @Description: Anonymous inner class * @author ADAM * @date July 25, 2014 Morning 10:38:25  * * /public class Anonymousinnerclass {public void click (Onclicklistener onclicklistener) {System.out.println ("click, Click ");} public static void Main (string[] args) {Anonymousinnerclass anonymousinnerclass = new Anonymousinnerclass (); Anonymousinnerclass.click (New Onclicklistener () {///Direct new out anonymous inner class, no need to save object, generally used to inherit other classes or Implement Interface @overridepublic void OnClick () {System.out.println ("Inner click");}});}}

Iv. Summary  As it is still in the learning stage, the most used internal classes are also members of the inner class and anonymous inner classes, so for example, very carefully to distinguish between the use of various internal classes and the role of the smaller access to the effect of such aspects are not very profound, after a further study will fill up, Also want to see this blog friend if there are some other ideas or supplements or recommendations to learn the information can also be proposed, this blog is also learn from the online gods and Encyclopedia of relevant information, and then their own manual code verification summed up, thank you the great God, thanks.



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.