匿名内部类也就是没有名字的内部类
正因为没有名字,所以匿名内部类只能使用一次,它通常用来简化代码编写
但使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口
使用匿名内部类课使代码更加简洁、紧凑,模块化程度更高。内部类能够访问外部内的一切成员变量和方法,包括私有的,而实现接口或继承类做不到。然而这个不是我说的重点,我说的很简单,就是匿名内部类的两种实现方式:第一种,继承一个类,重写其方法;第二种,实现一个接口(可以是多个),实现其方法。下面通过代码来说明:
实例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
再次总结:
- public class TestAnonymousInterClass{
- public static void main(String args[]){
- TestAnonymousInterClass test=new TestAnonymousInterClass();
- test.show();
- }
- //在这个方法中构造了一个匿名内部类
- private void show(){
- Out anonyInter=new Out(){// 获取匿名内部类实例
- void show(){//重写父类的方法
- System.out.println("this is Anonymous InterClass showing.");
- }
- };
- anonyInter.show();// 调用其方法
- }
- }
- // 这是一个已经存在的类,匿名内部类通过重写其方法,将会获得另外的实现
- class Out{
- void show(){
- System.out.println("this is Out showing.");
- }
- }
程序运行的输出结果为:
this is Anonymous InterClass showing.
所以在这里看出,匿名内部类有了自己的实现。其实很简单,使用匿名内部类是因为我这地方需要有点什么特殊的实现,所以我就在这地方把具体实现也给了出来了。然后我就在这地方获取它的实例,调用它的方法。
接口的方式,只要把父类换成接口就行了,没必要给出代码了。
使用匿名内部类时我们不要忘了我们的目的,我们只是在这地方想对某个类有特殊的实现。而不要想得太多,在匿名内部编写其它的方法。在匿名内部类中编写的自己的方法是不可见的。此种做法是毫无意义的,当然一般也不会这么做。在这里只是告诉初学者对于匿名内部类不要想的太多,而要这么想:匿名内部类就是重写父类或接口的方法。