匿名内部类就是当所需要定义的类只需要调用一次的情况下,为了简便的写法,定义不需要名字的匿名内部类。匿名内部类必须要继承一个父类或实现一个接口。
举例:
复制代码
1
2
3
4
// 父类
abstract class Animal {
public abstract void eat();
}
复制代码
1
2
3
4
5
6
// 子类
class Bird extends Animal{
public void eat() {
System.out.println("bird eat");
}
}
复制代码
1
2
3
4
5
6
public class main{
public static void main(String[] args) {
Animal animal =new Bird();
animal.eat();
}
}
这个例子中,Bird类在main函数中只调用一次,那么我们可以使用匿名内部类。把main函数中Animal animal =new Bird();改成匿名内部类定义。
复制代码
1
2
3
4
// 父类
abstract class Animal {
public abstract void eat();
}
复制代码
1
2
3
4
5
6
7
8
9
10
public class main{
public static void main(String[] args) {
Animal animal =new Animal(){
public void eat() {
System.out.println("bird eat");
}
};
animal.eat();
}
}
匿名内部类,最典型的应用在线程和定时器的应用上,如Thread、Runnable和TimerTask的使用。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
public class Test {
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
6
7
8
9
10
11
12
13
public class Test{
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();
}
}
最后
以上就是香蕉小鸭子最近收集整理的关于Java 匿名内部类的全部内容,更多相关Java内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复