Please go to DobbyKim’s Question of the Day for more questions
A:
Normal inner class:
- You can access all properties and methods of the external class
- A normal inner class cannot contain static properties and methods
Static inner class:
- A static inner class can access only static properties and methods of the outer class, not ordinary members (variables and methods) of the outer class
- Static inner classes can contain static properties and methods
So, do you know why a normal inner class can access a member variable of an outer class?
Let’s look at an example:
Home
package com.github.test;
public class Home {
class A {}}Copy the code
Home2
package com.github.test;
public class Home2 {
static class A {}}Copy the code
After compiling, we go to the target directory and look at the decompiled class files from Home and Home2
Execute command:
javap -private 'Home$A'
Copy the code
Home$A.class
class com.github.test.Home$A {
final com.github.test.Home this$0;
com.github.test.Home$A(com.github.test.Home);
}
Copy the code
Execute command:
javap -private 'Home2$A'
Copy the code
Home2$A.class
class com.github.test.Home2$A {
com.github.test.Home2$A();
}
Copy the code
We can see that the Home class contains the ordinary inner class A. After decompilating the class file, we can see A special field: com.github. Test. , this field is automatically added by the JDK for us, pointing to the external class Home.
So, it is clear that ordinary inner classes can access external class member variables directly because the JDK adds an implicit this$0 variable to the external class.
So, when should we use inner classes and when should we use static inner classes?
Item 24 of Effective Java says Favor static member classes over nonstatic, i.e., static inner classes are preferred.