Java中的匿名內部類

一般經過繼承某個類或實現某個接口的方式來編寫代碼,可是有時候某一些代碼只使用一次,就沒有必要寫專門寫一個子類或實現類了,能夠採用匿名內部類的寫法。最經常使用的場景是線程方面的應用。ide

1、不使用匿名內部類
①繼承
abstract class Player
{
 public abstract void play();
}this

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

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


2、使用匿名內部類
①繼承
abstract class Player
{
 public abstract void play();
}get

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

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

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

3、線程中的應用
實現線程的方法有兩種:①繼承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(); }}

相關文章
相關標籤/搜索