[Java] an in-depth understanding of internal classes: inner-classes

Source: Internet
Author: User

 

[Java] an in-depth understanding of internal classes: inner-classes

[Java] an in-depth understanding of internal classes: inner-classesTable of Contents
  • 1 Overview
  • 2 cases
    • 2.1 do not use the implementation of internal classes
    • 2.2 Implementation of internal classes
  • 3. Interesting things started to happen.
    • 3.1 extract member functions, variables, and constructors from class files
    • 3.2 explain why Internal classes can directly access member variables of external classes
  • 4. Local internal class implementation
  • 5 anonymous internal class
1 Overview

An internal class is a class defined in other classes. Why does it have such a feature?

The following are examples to explain the internal departments and classes in depth. We welcome your suggestions.

2 cases

In a primary school classroom, the math teacher teaches the children to count numbers. The teacher says a number, for example, n. Then the children start to count at intervals of n, such as 1, 1 + n, 1 + n ,..., When the teacher says stop, the child stops counting (Here we assume that the speed of the child's counting is even, 1 number/s ).

2.1 do not use the implementation of internal classes
Import java. awt. event. *; import javax. swing. *; public class Demo {public static void main (String [] args) {// For the sake of simplicity, // The Student name is directly defaulted here: xiao ming // the step of the number is 10 Student s = new Student ("xiao ming"); s. startCount (10); JOptionPane. showMessageDialog (null, "Stop count. "); System. exit (0) ;}}/** Student class, which only contains Student name information */class Student {public Student (String name) {this. name = name;} public void startCount (int step) {// In order to know who is Counting, // The Student name information must be passed to the Counting class ActionListener count = new Counting (step, name ); timer t = new Timer (1000, count); t. start ();} private String name;}/** is used to implement the count function at intervals */class Counting implements ActionListener {public Counting (int step, String name) {this. step = step; this. name = name; num = 1 ;}// public void action=med (ActionEvent event) {System. out. println (name + "count:" + num); num = num + step;} private int step; private int num; private String name ;}

 

In the preceding example, we found that if you use an external class to implement this function, the counting class can be used by other classes in the package, reducing the encapsulation of this function. this can be solved by using internal classes.

2.2 Implementation of internal classes
Import java. awt. event. *; import javax. swing. *; public class Demo {public static void main (String [] args) {// For the sake of simplicity, // The Student name is directly defaulted here: xiao ming // the step of the number is 10 Student s = new Student ("xiao ming"); s. startCount (10); JOptionPane. showMessageDialog (null, "Stop count. "); System. exit (0) ;}}/** Student class, which only contains Student name information */class Student {public Student (String name) {this. name = name;} public void startCount (int step) {// In order to know who is Counting, // The Student name information must be passed to the Counting class ActionListener count = new Counting (step); Timer t = new Timer (1000, count); t. start ();} private String name; /** used to implement the count function at intervals. In the internal class, you can directly use the member variable-name */private class Counting implements ActionListener {public Counting (int step) in the external class) {this. step = step; num = 1;} // counts public void actionreceivmed (ActionEvent event) {System. out. println (name + "count:" + num); num = num + step;} private int step; private int num ;}}

 

In this way, other classes in the package cannot directly call the Counting class.

3. Interesting things started to happen.

Example files generated after compilation using external classes are:

Demo.class, Student.class, Counting.class

The class file generated after the internal class example is:

Demo.class, Student.class, Student$Counting.class

From the compiled results alone, the Java Virtual Machine should have nothing to do with "external class implementation" and "internal class implementation" during the loading and implementation of specific classes. so "Student $ Counting. class "what exactly does this magic class contain?

Let's reveal this secret. The tool used is java decompiler.

The decompiled result is as follows: Student $ Counting. class:

# Studentcounting

Student. class:

# Student

From Student $ Counting. class, we found that one variable exists in the parameter list of its constructor:

// beforepublic Counting(int paramInt) {  this.step = paramInt;  this.num = 1;}// afterpublic Student$Counting(Student paramStudent, int paramInt) {  // ...}

But there is still no visualization. Who assigned this variable? It took more than two hours to find a more suitable software for reverse java compilation, but it didn't find the right software, java is used only to focus on the member variables and member functions within the class. lang. the class in reflect extracts class names, member variables, and functions from a class file.

3.1 extract member functions, variables, and constructors from class files

The reflect library contains three fields, Method and Constructor, which are used to obtain member variables, member functions, and Constructor. The specific implementation is as follows:

Import java. lang. reflect. *; import javax. swing. *; public class ReflectionTest {public static void main (String [] args) {// enter the file to be processed from the command line, or enter the String name by the user; if (args. length> 0) name = args [0]; else name = JOptionPane. showInputDialog ("Class name (e.g. java. util. date): "); try {// output Class name and parent Class cl = Class. forName (name); Class supercl = cl. getSuperclass (); System. out. print ("class" + name); if (su Percl! = Null & supercl! = Object. class) {System. out. print ("extends" + supercl. getName ();} System. out. print ("{\ n"); printConstructors (cl); System. out. println (); printMethods (cl); System. out. println (); printFields (cl); System. out. println ("}");} catch (ClassNotFoundException e) {e. printStackTrace () ;}}/** outputs all constructors of A Class */public static void printConstructors (Class cl) {Constructor [] constructors = cl. getDeclaredConstructors (); for (int I = 0; I <constructors. length; I ++) {Constructor c = constructors [I]; String name = c. getName (); System. out. print ("\ t" + Modifier. toString (c. getModifiers (); System. out. print ("" + name + "("); // output parameter type Class [] paramTypes = c. getParameterTypes (); for (int j = 0; j <paramTypes. length; j ++) {if (j> 0) System. out. print (","); System. out. print (paramTypes [j]. getName ();} System. out. println (");") ;}}/** output all member methods of a Class */public static void printMethods (Class cl) {Method [] methods = cl. getDeclaredMethods (); for (int I = 0; I <methods. length; I ++) {Method m = methods [I]; Class retType = m. getReturnType (); String name = m. getName (); System. out. print ("\ t" + Modifier. toString (m. getModifiers (); System. out. print ("" + retType. getName () + "" + name + "("); // output parameter type Class [] paramTypes = m. getParameterTypes (); for (int j = 0; j <paramTypes. length; j ++) {if (j> 0) System. out. print (","); System. out. print (paramTypes [j]. getName ();} System. out. println (");") ;}}/** output all member variables */public static void printFields (Class cl) {Field [] fields = cl. getDeclaredFields (); for (int I = 0; I <fields. length; I ++) {Field f = fields [I]; Class type = f. getType (); String name = f. getName (); System. out. print ("\ t" + Modifier. toString (f. getModifiers (); System. out. println ("" + type. getName () + "" + name + ";");}}}View Code

 

3.2 explain why Internal classes can directly access member variables of external classes

Run:

javac ReflectionTest.javajava ReflectionTest 'Student$Counting'

Output:

class Student$Counting {   public Student$Counting(Student, int);   public void actionPerformed(java.awt.event.ActionEvent);   private int step;   private int num;   final Student this$0;}

Then, combined with the result map of the class decompilation, we can find that by adding the Student variable to the constructor and assigning the valuefinal Student this$0This explainsWhy can I access the member variables of an external class in an internal class?But why can I accessPrivate variables of external classesWhat about it?

Let's take a look at another amazing place in Student $ Counting.

System.out.println(Student.access$000(this.this$0) + " count: " + this.num);

It can be seen that another member function is added to the Student class, but it is not found in the result of the Java Decompiler software. Therefore, the ReflectionTest is used again and the result is:

class Student {   public Student(java.lang.String);   public void startCount(int);   static java.lang.String access$000(Student);   private java.lang.String name;}

It can be seen that a new static method appears in the compiled Student. We can easily guess that the implementation of this static method is similar to the following:

static String access$000(Student s) {  return name;}

In this way, the compiler accesses the private variables of another class from one class. Then, by directly modifying the class file, it is possible to obtain or change the private variables in the class, of course, more powerful capabilities are required for implementation.

4. Local internal class implementation

When using a local internal class in code writing, other classes lose the ability to call it. Student is as follows:

/** Student class, which only contains the Student name information */class Student {public Student (String name) {this. name = name;} public void startCount (final int step) {/** is used to implement the count function at intervals. In a local internal class, you can directly use the member variable-name in the external class or call the final local variable */class Counting implements ActionListener. {// public void actionreceivmed (ActionEvent event) {System. out. println (name + "count:" + num); num = num + step;} private int num = 1 ;} // In order to know who is Counting, // The Student name information must be passed to the Counting class ActionListener count = new Counting (); Timer t = new Timer (1000, count ); t. start () ;}private String name ;}

 

The newly generated classes after compilation are:

Demo.class  Student$1Counting.class  Student.class

Continue to use ReflectionTest to process the last two class files. The results are as follows:

// Student$1Counting.classclass Student$1Counting {     Student$1Counting(Student, int);    public void actionPerformed(java.awt.event.ActionEvent);    private int num;    final int val$step;    final Student this$0;}// Student.classclass Student {    public Student(java.lang.String);    public void startCount(int);    static java.lang.String access$000(Student);    private java.lang.String name;}

After compilation, local variables and external classes become member variables of internal classes. The availability of local variables makes the entire program simpler and clearer.

5 anonymous internal class

The implementation of anonymous internal classes can also be implemented in a similar way.

The implementation format of anonymous internal classes is as follows:

new SuperType(construction parameters) {  inner class methods and data}

In fact, you can have a clearer understanding of anonymous internal classes through the following methods:

Person count = new class extends Person (""){...}; // This form is not a real java format, just to help understand Person count = new Person (""){...}; // This is the correct format

An anonymous internal class is also commonly used to initialize a variable using the initialization block:

Private List <String> maleList = new ArrayList <String> () {// initialization block {add ("Machael"); add ("Scorfield "); add ("Other ");}};

To better understand the above initialization blocks, you can continue to look at the following example:

Class Person {private String name; {System. out. println ("initialization block in class Person");} public Person () {this. name = null;} public Person (String name) {setName (name);} public void setName (String name) {this. name = name;} public String getName () {return name;} public class Demo {public static void main (String [] args) {Person p1 = new Person ("xiao ming"); System. out. println ("direct initialization:" + p1.getName (); System. out. println (); Person p2 = new Person () {// initialization block {System. out. println ("initialize block in Anonymous class"); setName ("xiao ming") ;}}; System. out. println ("Double parenthesis initialization:" + p2.getName ());}}

 

The result is:

Initialization block in class Person direct initialization: xiao ming initialization block in class Person initialization block in Anonymous class double parentheses initialization: xiao ming
Footnotes:

1 book Core Java,: download

 

Supplement:

Comparison between Anonymous class initialization and direct operations, see http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization

 

Date: 2014-05-19 Mon

Author: Zhong Xiewei

Org version 7.8.11 with Emacs version 24

Validate XHTML 1.0

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.