通常通过继承某个类或实现某个接口的方式来编写代码,但是有时候某一些代码只使用一次,就没有必要写专门写一个子类或实现类了,可以采用匿名内部类的写法。最常用的场景是线程方面的应用。
一、不使用匿名内部类
①继承
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();