定义
匿名类,就是没有过名称的类,其名称由 java编译器 给出。一般是:外部类名称+$+匿名类顺序。没有名称就是其他地方不能引用,不能实例化,也不能有 构造器 。
匿名内部类示例
interface StudentInterface {
String getInfo();
}
@Data
public class AnonymousStudent {
private String no;
private String name;
public String getCard() {
StudentInterface info = new StudentInterface() {
@Override
public String getInfo() {
return no + "_" + name;
}
};
return info.getInfo();
}
public String getCard(StudentInterface studentInterface) {
return studentInterface.getInfo();
}
public static void main(String[] args) {
AnonymousStudent student = new AnonymousStudent();
student.setNo("no000001");
student.setName("name00001");
System.out.println("匿名类,方式一" + student.getCard());
String result = student.getCard(new StudentInterface() {
@Override
public String getInfo() {
return student.no + student.name;
}
});
System.out.println("匿名类,方式二:" + result);
}
}
匿名内部类的特点
- 匿名类有上述两种主要实现方式。
- 匿名内部类只能使用一次,不区分static和非static。如果用到外部类的变量的话,必须是类变量或者实例变量,就是必须是类定义的变量,或者final的局部变量。
- 匿名内部类如果是继承某个类的时候,可以重写那个类的方法。
- 可以使用匿名内部类的地方,都可以替换为内部类。
- 匿名类的类体不可以声明static成员变量和static方法。