需要加修饰符static;
可以定义静态成员和非静态成员;
不能直接访问包围类的非静态成员,可直接访问包围类的静态成员;
可以通过包围类的对象进行访问非静态成员;
外界可以通过静态嵌套类名访问其静态成员,通过对象访问其非静态成员;
外界需要通过包围类才可以访问到静态嵌套类,并创建其对象,不需要外部包围类的实例;
和正常的类没有什么区别,纯粹只是为了打包的便利性存在;
public class Outer1 {
String name;
//静态嵌套类
static class Inner1{
String name;
}
}
---测试类
public class MyTest1 {
public static void main(String[] args) {
Outer1.Inner1 obj = new Outer1.Inner1();
//第三方需要通过外部包围类才可以访问到静态嵌套类
}
}
静态内部类分析
----测试类
public class Outer2Test {
public static void main(String[] args) {
//第三方类访问静态嵌套类
Outer2.Inner1 obj1 = new Outer2.Inner1();
obj1.getInnFlied1();
Outer2.Inner1 obj2 = new Outer2.Inner1();
System.out.println(obj1 == obj2);
System.out.println("===================");
Outer2 obj3 = new Outer2();
obj3.outFun2();
/*false
===================
false
inner 333
inner hello
inner static 444*/
}
}
----静态内部类
public class Outer2 {
private static String outStaticFiled2 = "outer static 222";
private String outFiled = "outer 111";
public void outFun2() {
Inner1 obj1 = new Inner1();
Inner1 obj2 = new Inner1();
System.out.println(obj1 == obj2);//false
System.out.println(obj1.getInnFlied1());//inner 333
System.out.println(Inner1.getInnerStaticFiled2());//inner static 444
}
public String getOutFiled() {
return this.outFiled;
}
//静态嵌套类
// private static class Inner1
// static class Inner1
// protected static class Inner1
public static class Inner1 {
static String innerStaticFiled2 = "inner static 444";
//静态嵌套类可以定义静态的、非静态的成员
private String innFlied1 = "inner 333";
public static String getInnerStaticFiled2() {
hello();
//Outer2.hello();
return innerStaticFiled2;
}
private static void hello() {
System.out.println("inner hello");
}
public String getInnFlied1() {
return innFlied1;
}
public void innFun1() {
//静态嵌套类可以直接访问包围类的静态成员
System.out.println(outStaticFiled2);
//System.out.println(outFiled);--error
//静态嵌套类可以通过对象访问包围类的非静态成员
Outer2 obj = new Outer2();
System.out.println(obj.getOutFiled());
}
}
}