• Java 匿名类


    匿名内部类也就是没有名字的内部类,匿名内部类只能使用一次,它通常用来简化代码编写,但使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口。

    实例1:不使用匿名内部类来实现抽象方法

     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
    abstract class Animal {
        public abstract void run();
    }
     
    class sheep extends Animal {
        public void run() {
            System.out.println("running fast");
        }
    }
     
    public class Demo {
        public static void main(String[] args) {
            Animal a = new Sheep();
            a.run();
        }
    }

    运行结果:running fast

    可以看到,我们用Sheep继承了Animal类,然后实现了Sheep的一个实例,将其向上转型为Animal类的引用

    但是,如果此处的Sheep类只使用一次,那么将其编写为独立的一个类岂不是很麻烦?

    这个时候就引入了匿名内部类

    实例2:匿名内部类的基本实现

     
     
     
     
     
     
     
     
     
     
     
     
     
    abstract class Animal {
        public abstract void run();
    }
     
    public class Demo {
        public static void main(String[] args) {
            Animal a = new Animal() {
                public void run() {
                    System.out.println("running fast");
                }
            };
            a.run();
        }
    }

    运行结果:running fast

    可以看到,我们直接将抽象类Animal中的方法在大括号中实现了

    这样便可以省略一个类的书写

    并且,匿名内部类还能用于接口上

     

    实例3:在接口上使用匿名内部类

    interface Animal {
        public void run();
    }
     
    public class Demo {
        public static void main(String[] args) {
           Animal a = new Animal() {
                public void run() {
                    System.out.println("running fast");
                }
            };
            a.run();
        }
    }

    运行结果:running fast

    由上面的例子可以看出,只要一个类是抽象的或是一个接口,那么其子类中的方法都可以使用匿名内部类来实现

    最常用的情况就是在多线程的实现上,因为要实现多线程必须继承Thread类或是继承Runnable接口

    实例4:Thread类的匿名内部类实现

    public class Demo {
        public static void main(String[] args) {
            Thread t = new Thread() {
                public void run() {
                    for (int i = 1; i <= 5; i++) {
                        System.out.print(i + " ");
                    }
                }
            };
            t.start();
        }
    }

    运行结果:1 2 3 4 5

    实例5:Runnable接口的匿名内部类实现

     
    public class Demo {
        public static void main(String[] args) {
            Runnable r = new Runnable() {
                public void run() {
                    for (int i = 1; i <= 5; i++) {
                        System.out.print(i + " ");
                    }
                }
            };
            Thread t = new Thread(r);
            t.start();
        }
    }

    运行结果:1 2 3 4 5

  • 相关阅读:
    matlab中关于使用length导致的不稳定状况。
    matlab 批量读入文件夹中的指定文件类型 (目录级数不限)
    matlab中的图像裁剪,图像抽取,反转,镜像。
    反锐化掩模 unsharp masking【转载】
    matlab 将图像切分为N*N像素的小块
    Python2.7.3 Tkinter Entry(文本框) 说明
    基于JQuery的列表拖动排序
    MAC如何删除开机自启动程序
    MAC配置SVN服务器
    关于MAC清倒废纸篓,项目正在使用
  • 原文地址:https://www.cnblogs.com/hm1990hpu/p/7902743.html
Copyright © 2020-2023  润新知