Java语言容许在类中再定义类,这种在其它类内部定义的类就叫内部类。html
有static关键字修饰的内部类。python
好比:Pattern类中的Node类。测试
public class Outer { private static String s1 = "this is s1 in Outer"; private static String s2 = "this is s2 in Outer"; public void method1() { // 外部类可经过内部类的对象调用内部类的私有成员变量或方法 System.out.println(new Inner().s1); System.out.println(new Inner().method2()); } private static String method2() { return "this is method2 in Outer"; } // 内部静态类 public static class Inner { private String s1 = "this is s1 in Inner"; private static String s3 = "this is s3 in Inner"; public void method1() { // 内部类可直接访问外部类的私有静态成员变量或方法 System.out.println(s2); // 内部类和外部类有同名变量和方法时 System.out.println(s1); System.out.println(Outer.s1); System.out.println(method2()); System.out.println(Outer.method2()); } private String method2() { return "this is method2 in Inner"; } } }
------外部类测试--------
this is s1 in Inner this is method2 in Inner ------内部类测试-------- this is s2 in Outer this is s1 in Inner this is s1 in Outer this is method2 in Inner this is method2 in Outer
一、建立静态内部类方式:Outer.Inner inner = new Outer.Inner();静态内部类不依赖于外部类。this
二、外部类可经过内部类的对象调用内部类的私有成员变量或方法。spa
三、静态内部类访问的外部类成员变量或方法为何不能是非静态的,而成员内部类能够?htm
成员内部类中有外部类的引用,因此成员内部类对外部类的私有非静态变量和方法能够随意访问。对象
从静态内部类它不存在对外部类的引用,因此仅能访问外部类的静态成员变量或方法。blog
四、静态内部类中可定义静态的成员变量和方法。io
一、建立静态内部类方式:Outer.Inner inner = new Outer.Inner();静态内部类不依赖于外部类。class
二、外部类可经过内部类的对象调用内部类的私有成员变量或方法。
三、静态内部类访问外部类的静态成员变量或方法必须是静态的。
四、静态内部类中可定义静态的成员变量和方法。
五、外部类能够建立静态内部类的实例,即便是私有的;并可经过内部类的实例访问内部类的成员变量和方法,即便是私有的。
1)首先,用内部类是由于内部类与所在外部类有必定的关系,每每只有该外部类调用此内部类。因此没有必要专门用一个Java文件存放这个类。
2)静态都是用来修饰类的内部成员的。好比静态方法,静态成员变量,静态常量。它惟一的做用就是随着类的加载(而不是随着对象的产生)而产生,以至能够用类名+静态成员名直接得到。
这样静态内部类就能够理解了,由于这个类没有必要单独存放一个文件,它通常来讲只被所在外部类使用。而且它能够直接被用 外部类名+内部类名 得到。
3)普通内部类把它理解为与外部类绑定了,建立普通内部类对象必定要经过外部类的对象new才行。而静态内部类是不须要的
#参考
https://www.cnblogs.com/SQP51312/p/6102620.html
https://zhidao.baidu.com/question/149873207.html