您的位置 首页 java

java-匿名类示例及其特点

java-匿名类示例及其特点

定义

匿名类,就是没有过名称的类,其名称由 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);
 }
}  

匿名内部类的特点

  1. 匿名类有上述两种主要实现方式。
  2. 匿名内部类只能使用一次,不区分static和非static。如果用到外部类的变量的话,必须是类变量或者实例变量,就是必须是类定义的变量,或者final的局部变量。
  3. 匿名内部类如果是继承某个类的时候,可以重写那个类的方法。
  4. 可以使用匿名内部类的地方,都可以替换为内部类。
  5. 匿名类的类体不可以声明static成员变量和static方法。

文章来源:智云一二三科技

文章标题:java-匿名类示例及其特点

文章地址:https://www.zhihuclub.com/182701.shtml

关于作者: 智云科技

热门文章

网站地图