通常通過繼承某個類或實作某個接口的方式來編寫代碼,但是有時候某一些代碼隻使用一次,就沒有必要寫專門寫一個子類或實作類了,可以采用匿名内部類的寫法。最常用的場景是線程方面的應用。
一、不使用匿名内部類
①繼承
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
iplayer ip1 = new iplayfootballimpl();
ip1.play();
二、使用匿名内部類
player p2 = new player() {
system.out.println("打籃球");
};
p2.play();
iplayer ip2 = new iplayer() {
三、線程中的應用
實作線程的方法有兩種:①繼承thread類 ②實作runnable接口。給出用匿名類實作的例子:
public class threadtest
// 繼承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() {
});
thread2.start();