Fork me on GitHub

匿名内部类

Posted on 2019-09-03 18:58  攀一座山  阅读(235)  评论(0编辑  收藏  举报

1、匿名内部类:没有名字,只有唯一的对象,在声明类的同时就创建好了这个对象。

2、语法格式:

new 父类(){
    成员列表
}

new 父类(实参列表){
    成员列表
}

new 父接口(){
    
}

  

3、使用匿名内部类的形式一般是三种

(1)多态引用:通过父类或父接口的变量对匿名内部类的对象进行多态引用

多态引用,只能重写父类或父接口的方法,才能调用到,否则自己扩展的方法是无法调用的。

interface A{
    void a();
}

A obj = new A(){
    public void a(){
        //.....
    }  
};

obj.a();

  

class Father{
    public void method(){
        //...
    }
}

Father f = new Father(){
  public void method(){
      //....
  }  
};

f.method();

  (2)匿名内部类的匿名对象直接调用方法

new Object(){
    public void test(){
        //...
    }
}.test();

//这个test方法不是父类Object类中的,只能这么调用

  (3)匿名内部类的匿名对象作为方法调用的“实参”

class Student{
    private int id;
    private String name;
    private int score;
    //...
}

Student[] arr = new Student[3];
arr[0] = new Student(1,"张三",89);
arr[1] = new Student(2,"李四",80);
arr[2] = new Student(3,"王五",86);

//按照成绩从高到低
Arrays.sort(arr, new Comparator(){
    public int compare(Object o1, Object o2){
        Student s1 = (Student)o1;
        Student s2 = (Student)o2;
        return s2.getScore() - s1.getScore();
    }
});

  

Copyright © 2024 攀一座山
Powered by .NET 8.0 on Kubernetes