zoukankan      html  css  js  c++  java
  • 匿名内部类

    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();
        }
    });
    

      

  • 相关阅读:
    广播BroadcastReceiver(2)
    hunnu11544:小明的烦恼——找字符串
    Systemd启动图形界面过程
    大数据.......
    2014百度之星第一题Energy Conversion
    基于zookeeper简单实现分布式锁
    LeetCode OJ 215. Kth Largest Element in an Array 堆排序求解
    Leetcode
    Linux文件系统(七)---系统调用之open操作(一)
    Go语言Slice操作.
  • 原文地址:https://www.cnblogs.com/panyizuoshan/p/11454884.html
Copyright © 2011-2022 走看看