前言
Java拥有四种内部类:静态内部类,成员内部类,局部内部类和匿名内部类。
1. 静态内部类
静态内部类有static
修饰,被声明为外部类的静态成员,它的行为和一般的类是一样的。在接口中的内部类都是静态内部类。静态内部类是外部类的成员,可以访问外部类的所有成员,包括私有成员。
public class Super {
private int iValue = 1;
public static class StaticInner {
void print(Super sup) {
System.out.println(sup.iValue);
}
}
public static void main(String[] args) {
Super sup = new Super();
new StaticInner().print(sup); // 1
}
}
2. 成员内部类
成员内部类没有static
做修饰,但它同样可以访问外部类的成员。内部类也可以通过this
来访问外部类的成员。
public class Super {
private int iValue = 1;
public class Inner {
void print() {
System.out.println(iValue); // 1
System.out.println(Super.this.iValue); // 1
}
}
public static void main(String[] args) {
Super sup = new Super();
Inner inner = sup.new Inner();
inner.print();
}
}
内部类也可以继承,唯一的要求是扩展类的对象必须要和最初的外部类或其子类的对象相关联。
public class ExtendSuper extends Super {
Inner inner = new ExtendInner();
public class ExtendInner extends Inner {
}
}
如果内部类的子类没有外部类,那么必须提供一个包含类的显示引用。
public class Unrelated extends Super.Inner {
public Unrelated(Super sup) {
sup.super();
}
}
内部类会隐藏相同名称的外部成员
public class Super {
private int iValue = 1;
public class Inner {
private int iValue = 2;
void print() {
System.out.println(iValue); // 2
System.out.println(Super.this.iValue); // 1
}
}
public static void main(String[] args) {
Super sup = new Super();
Inner inner = sup.new Inner();
inner.print();
}
}
3. 局部内部类
在代码块中定义内部类,这些内部类就像局部变量一样,在代码块的外部是无法访问的。局部内部类可以访问外部类的所有成员,唯一的限制是局部变量只有被声明为final
时才可以访问。在print()
方法中定义了Thread
的局部内部类。
public class Super {
private int iValue = 1;
public void print() {
final String strValue = "strValue";
Thread thread = new Thread() {
public void run() {
System.out.println(iValue); // 1
System.out.println(strValue); // strValue
}
};
thread.start();
}
public static void main(String[] args) {
Super sup = new Super();
sup.print();
}
}
4. 匿名内部类
匿名内部类是没有命名的局部内部类。
public class Super {
private int iValue = 1;
public void print() {
final String strValue = "strValue";
new Thread() {
public void run() {
System.out.println(iValue); // 1
System.out.println(strValue); // strValue
}
}.start();
}
public static void main(String[] args) {
Super sup = new Super();
sup.print();
}
}