First, what is nested class and internal class?
You can define another class within a class, called a nested class (nested classes), which has two types:
Static nested classes and non-static nested classes. Static nested classes use few, most important, non-static nested classes, which are called internal classes (inner). Nested classes are introduced from JDK1.1. Among them, inner class can be divided into three kinds:
One, the internal class directly defined in a class (external class);
The inner class defined in a method (the method of an external class);
Its three, anonymous inner class.
Below, I will explain the use of these nested classes and considerations.
Second, Static nesting class
The code shown below is defined as a static nested class.
public class StaticTest {
private static String name = "javaJohn";
private String id = "X001";
static class Person{
private String address = "swjtu,chenDu,China";
public String mail = "josserchai@yahoo.com";//内部类公有成员
public void display(){
//System.out.println(id);//不能直接访问外部类的非静态成员
System.out.println(name);//只能直接访问外部类的静态成员
System.out.println("Inner "+address);//访问本内部类成员。
}
}
public void printInfo(){
Person person = new Person();
person.display();
//System.out.println(mail);//不可访问
//System.out.println(address);//不可访问
System.out.println(person.address);//可以访问内部类的私有成员
System.out.println(person.mail);//可以访问内部类的公有成员
}
public static void main(String[] args) {
StaticTest staticTest = new StaticTest();
staticTest.printInfo();
}
}
Within a static nested class, non-static members of the outer class cannot be accessed, as defined by "static methods cannot directly access Non-static members" in the Java syntax.
If you want to access the variables of the external class, you must solve them by other means, for this reason, the static nesting classes are rarely used. Note that the members of the external class that access the inner class are somewhat special and cannot be accessed directly, but can be accessed through an inner class, because all members and methods within the static nesting are static by default. Also note that the internal static class person is visible only within the statictest scope of the class, and is incorrect if referenced or initialized in other classes.