歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Java中的匿名內部類

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

Java 8簡明教程 http://www.linuxidc.com/Linux/2014-03/98754.htm

Java對象初始化順序的簡單驗證 http://www.linuxidc.com/Linux/2014-02/96220.htm

Java對象值傳遞和對象傳遞的總結 http://www.linuxidc.com/Linux/2012-12/76692.htm

Java對象序列化ObjectOutputStream和ObjectInputStream示例 http://www.linuxidc.com/Linux/2012-08/68360.htm

一、不使用匿名內部類
①繼承
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();
}
}

Copyright © Linux教程網 All Rights Reserved