The biggest difference between a regular inner class and a normal class is that it can access the private instance domain of an external class. Here is an example:
Package Innerclass;public class Outer {private Boolean Isprint;public Outer (Boolean isprint) {this.isprint = Isprint;} public void Useinnermethod () {Outer.Inner Inner = this.new Inner ();//equivalent to Inner Inner = new Inner (); Inner.innerprint ();} public class Inner {public void Innerprint () {//inner class can access private instance domain of external class if (Outer.this.isPrint) {//= equivalent to if (isprint) {SYSTEM.OUT.P Rintln ("Print Ture");} else {System.out.println ("Print Flase");}}}}
Package Innerclass;public class Testouter {public static void main (string[] args) {//TODO auto-generated method Stubouter outer = new outer (false); Outer.useinnermethod ();//The Inner class object must depend on the Outer class object outer outer1 = new outer (true); outer. Inner Inner = Outer1.new Inner (); Equivalent to inner inner = outer1.new inner (); Inner.innerprint ();}}
The result of running Testouter is:
Print Flase
Print Ture
Why do internal classes have access to private instance domains that access external classes? We decompile and compile the two class files obtained by the outer class to get the answer.
Run Javap-private Outer at the command line to get the following result:
Warning:binary file Outer contains Innerclass. Outercompiled from the "Outer.java" public class Innerclass. Outer { private boolean isprint; Public Innerclass. Outer (Boolean); public void Useinnermethod (); Static Boolean access$0 (Innerclass. Outer);}
run-private outer$inner at the command line to get the following result:
Warning:binary file Outer$inner contains Innerclass. Outer$innercompiled from the "Outer.java" public class Innerclass. Outer$inner { final innerclass. Outer this$0; Public Innerclass. Outer$inner (Innerclass. Outer); public void Innerprint ();}
By reading the results of the anti-compilation, we know that the compiler added a reference to an external class object in the inner class:
Final Innerclass. Outer this$0;
we know that even if we have a reference to an object, we cannot pass the. (point) to manipulate the private instance domain of the object directly, then how does the inner class do it? We see that the compiler also added a method to the outer class:
Static Boolean access$0 (Innerclass. Outer);
The inner class is implemented by this method to access the private instance domain of the external class.
Java Inner Class (i) General inner class