In "In-depth analysis based on the role of java internal classes" you can understand some things about java internal classes, but there are still some places in internal classes worthy of our careful study...
Below are some things about Java internal classes that I have summarized and share with you....
one: Static inner classes can have static members, but non-static inner classes cannot have static members.
How to understand this?
Take a look at the code below:
public class Test {
private int number = 1;
// Non-static inner classes can have non-static members
private class InnerTest {
// error Non-static inner classes cannot have static members
// private static int inNumber = 2;
private int inNumber = 2;
public InnerTest() {
setNumber(2);
inNumber = inNumber + number;
System.out.println("innerTest---" + inNumber);
}
}
//Private method of Test
private void setNumber(int number) {
this.number = number;
}
//Constructor
public Test() {
InnerTest in = new InnerTest();
System.out.println("test");
}
public static void main(String[] args) {
Test test = new Test();
// innerTest---4
// test
}
}
public class Test {
private static int number = 1;
private String name = "test";
// static inner class
private static class InnerTest {
// Static inner classes can have non-static members
private int inNumber = 2;
public InnerTest() {
//Static inner classes can access static members of outer classes
setNumber(2);
inNumber = inNumber + number;
System.out.println("innerTest---" + inNumber);
//error static inner class cannot access non-static members of outer class
//System.out.println(name);
}
}
//Static private method of Test
private static void setNumber(int n) {
number = n;
}
//Constructor
public Test() {
InnerTest in = new InnerTest();
System.out.println("test");
}
public static void main(String[] args) {
Test test = new Test();
// innerTest---4
// test
}
}
Is it easy to understand...
To summarize: