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();
}
}
最后更新:2017-04-04 07:32:25
上一篇:
XML(1)——shema约束之命名空间
下一篇:
linux/Aix启动、关闭Oracle及监听
Flurry:2012年美国和中国移动市场最具潜力
行业资深专家切身经验——给数据科学家新手的建议
大规模中文概念图谱CN-Probase正式发布
捡到iPhone7怎么解锁?手机锁屏了密码忘了怎么办?
解决Conversion to Dalvik format failed with error 1
js中的Window对象
穿着华丽的死人
Android源码研究的准备工作 -- 下载android源码到Ubuntu上(亲自调试,不能过分迷信GOOGLE文档)
大数据全真案例带你来解密如何挑选“风水宝地”
了解ASP.NET MVC几种ActionResult的本质:JavaScriptResult & JsonResult