总结:
1、匿名内部类不能定义任何静态成员、方法
2、匿名内部类中的方法不能是抽象的
3、匿名内部类必须实现接口或抽象父类的所以抽象方法
4、匿名内部类不能定义构造器
5、匿名内部类访问的外部类成员变量或成员方法必须用static修饰;
6、内部类可以访问外部类私有变量和方法
代码
接口
public interface Inner {
public String say();
}
抽象类
public abstract class Inner1 implements Inner {
}
普通类
public class Inner2 implements Inner {
public String say() {
return "this is Inner2";
}
}
外部类
public class Outer {
public static String s1 = "this is s1 in Outer";
public static String s2 = "this is s2 in Outer";
private static String s3 = "this is s3 in Outer";
public void method1(Inner inner) {
System.out.println(inner.say());
}
private static String method2() {
return "this is method2 in Outer";
}
public static void main(String[] args) {
Outer outer = new Outer();
// 测试1,Inner为接口
outer.method1(new Inner() {
String s1 = "this is s1 in Inner";
public String say() {
// 外部类和匿名函数类中有同名变量s1
return s1;
}
});
// 测试2,Inner1为抽象类
outer.method1(new Inner1() {
String s2 = "this is s2 in Inner1";
public String say() {
// 外部类和匿名函数类中有同名变量s2
return Outer.s2;
}
});
// 测试3,Inner2为普通类
outer.method1(new Inner2() {
public String say() {
// 访问外部类私有变量s3
return s3;
}
});
// 测试4,Inner2为普通类
outer.method1(new Inner2() {
public String say() {
// 访问外部类私有方法method1()
return method2();
}
});
}
}
结果