匿名内部类也就是没有名字的内部类html
正由于没有名字,因此匿名内部类只能使用一次,它一般用来简化代码编写java
但使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口多线程
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 somethingspa
能够看到,咱们用Child继承了Person类,而后实现了Child的一个实例,将其向上转型为Person类的引用线程
可是,若是此处的Child类只使用一次,那么将其编写为独立的一个类岂不是很麻烦?code
这个时候就引入了匿名内部类htm
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 somethingblog
能够看到,咱们直接将抽象类Person中的方法在大括号中实现了继承
这样即可以省略一个类的书写接口
而且,匿名内部类还能用于接口上
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接口
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
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