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

    通常通过继承某个类或实现某个接口的方式来编写代码,可是有时候某一些代码仅仅使用一次,就没有必要写专门写一个子类或实现类了,能够採用匿名内部类的写法。最经常使用的场景是线程方面的应用。

    一、不使用匿名内部类
    ①继承
    abstract class Player
    {
    public abstract void play();
    }

    public class FootBallPlayer extends Player
    {
    public void play()
    {
    System.out.println("踢足球");
    }
    }

    public class AnonymousInnerClassTest
    {
    public static void main(String[] args)
    {
    Player p1 = new FootBallPlayer();
    p1.play();
    }
    }

    ②接口
    interface IPlayer
    {
    public void play();
    }

    public class IPlayFootballImpl implements IPlayer
    {
    public void play()
    {
    System.out.println("踢足球");
    }
    }

    public class AnonymousInnerClassTest
    {
    public static void main(String[] args)
    {
    IPlayer ip1 = new IPlayFootballImpl();
    ip1.play();
    }
    }


    二、使用匿名内部类
    ①继承
    abstract class Player
    {
    public abstract void play();
    }


    public class AnonymousInnerClassTest
    {
    public static void main(String[] args)
    {
    Player p2 = new Player() {
    public void play()
    {
    System.out.println("打篮球");
    }
    };
    p2.play();
    }
    }

    ②接口
    interface IPlayer
    {
    public void play();
    }

    public class AnonymousInnerClassTest
    {
    public static void main(String[] args)
    {
    IPlayer ip2 = new IPlayer() {
    public void play()
    {
    System.out.println("打篮球");
    }
    };
    }
    }

    三、线程中的应用
    实现线程的方法有两种:①继承Thread类 ②实现Runnable接口。给出用匿名类实现的样例:

    public class ThreadTest
    {
    public static void main(String[] args)
    {
    // 继承Thread类
    Thread thread = new Thread() {
    @Override
    public void run()
    {
    while (true)
    {
    try
    {
    Thread.sleep(1000);
    System.out.println(Thread.currentThread().getName());
    System.out.println(this.getName());
    }
    catch (InterruptedException e)
    {
    System.out.println(e.getMessage());
    }
    }
    }
    };
    thread.start();

    // 实现Runnable接口
    Thread thread2 = new Thread(new Runnable() {
    @Override
    public void run()
    {
    while (true)
    {
    try
    {
    Thread.sleep(1000);
    System.out.println(Thread.currentThread().getName());
    }
    catch (InterruptedException e)
    {
    System.out.println(e.getMessage());
    }
    }
    }
    });
    thread2.start();
    }
    }
  • 相关阅读:
    SQL 分页存储
    ubuntu下删除openjdk,改用sun jdk
    LCD 驱动的整体分析。
    关于IT行业人员吃的都是青春饭?[透彻讲解]
    【转载】I.MX25上摄像头调试总结
    wifi 移植
    函数指针的透彻分析
    关于module_param()宏 (转)
    problem with aptget update ubuntu 11.10
    YUV 格式讲解
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4062330.html
Copyright © 2011-2022 走看看