java匿名内部类 (转载)
2024-09-05 22:45:11
匿名内部类也就是没有名字的内部类
正因为没有名字,所以匿名内部类只能使用一次,它通常用来简化代码编写
但使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口
实例1:不使用匿名内部类来实现抽象方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
abstract class Person { public abstract void eat(); } class Child extends Person { public void eat() { System.out.println( "eat something" ); } } public class Demo { public static void main(String[] args) { Person p = new Child(); p.eat(); } } |
运行结果:eat something
可以看到,我们用Child继承了Person类,然后实现了Child的一个实例,将其向上转型为Person类的引用
但是,如果此处的Child类只使用一次,那么将其编写为独立的一个类岂不是很麻烦?
这个时候就引入了匿名内部类
实例2:匿名内部类的基本实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
abstract class Person { public abstract void eat(); } public class Demo { public static void main(String[] args) { Person p = new Person() { public void eat() { System.out.println( "eat something" ); } }; p.eat(); } } |
运行结果:eat something
可以看到,我们直接将抽象类Person中的方法在大括号中实现了
这样便可以省略一个类的书写
并且,匿名内部类还能用于接口上
实例3:在接口上使用匿名内部类
interface Person { public void eat(); } public class Demo { public static void main(String[] args) { Person p = new Person() { public void eat() { System.out.println( "eat something" ); } }; p.eat(); } } |
运行结果:eat something
由上面的例子可以看出,只要一个类是抽象的或是一个接口,那么其子类中的方法都可以使用匿名内部类来实现
最常用的情况就是在多线程的实现上,因为要实现多线程必须继承Thread类或是继承Runnable接口
实例4:Thread类的匿名内部类实现
public class Demo { public static void main(String[] args) { Thread t = new Thread() { public void run() { for ( int i = 1 ; i <= 5 ; i++) { System.out.print(i + " " ); } } }; t.start(); } } |
运行结果:1 2 3 4 5
实例5:Runnable接口的匿名内部类实现
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class Demo { public static void main(String[] args) { Runnable r = new Runnable() { public void run() { for ( int i = 1 ; i <= 5 ; i++) { System.out.print(i + " " ); } } }; Thread t = new Thread(r); t.start(); } } |
运行结果:1 2 3 4 5
转自:
http://www.cnblogs.com/nerxious/archive/2013/01/25/2876489.html
最新文章
- Backbone源码学习之extend
- 修改Shp文件名称
- ubuntu rhythmbox乱码解决方法
- Emmet基本使用方法
- 【HDOJ】【3480】Division
- 转自知乎,亲民好酒推荐 分类: fool_tree的笔记本 2014-11-08 17:37 652人阅读 评论(0) 收藏
- poj1458 求最长公共子序列 经典DP
- H面试程序(12): 输出字符串中第一个只出现一次的字母
- struts2错误验证
- hdu 5344 MZL&#39;s xor
- HDU 6140 Hybrid Crystals
- 记录一下自己爬虎牙LOL主播的爬虫思路
- excel表格获取汉字大写首拼函数(自定义宏)
- 【Tomcat】Tomcat相关设计模式分析
- Content-Length mismatch, received 431737 bytes out of the expected 760836
- Css3新属性:calc()
- usart2 重映射
- 1. dubbo概述
- [转贴]CentOS7.5 Kubernetes V1.13(最新版)二进制部署集群
- 133克隆图 &#183; Clone Graph
热门文章
- 【C++进阶:STL常见性质3】
- Ueditor1.4.4 Jsp版本视频上传成功,重新编辑时无法打开、在文本框内无法显示、html源码显示src为空
- leetcode 40. 组合总和 II (python)
- Vue知识整理1:$watch方法的使用
- gradle implementation runtimeOnly 和api 区别
- hacker101教学笔记--introduction--the web in depth
- centos7下安装iperf时出现 make: *** No targets specified and no makefile found. Stop.的解决方案
- javascript详细介绍
- Tunnel Warfare HDU 1540 区间合并+最大最小值
- 错排问题 &;&; 洛谷 P1595 信封问题