Java进阶-匿名内部类

  1. 匿名内部类,指 类没有名字
  2. 优点:少定义一个类
  3. 缺点:无法复用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Test {
// 静态方法
public static void t(CustomerService cs) {
cs.logout();
}

public static void main(String[] args) {
// 使用匿名内部类的方法执行 t 方法
// 整个 new CustomerServie(){} 就是一个匿名内部类
t(new CustomerService() {
public void logout() {
System.out.println("Exit!"); //输出:Exit!
}
});

// 不用匿名内部类的实现
t(new CustomerServiceImpl());
}
}

// 接口
interface CustomerService {
// 退出系统
void logout();
}

// 编写一个类实现 CustomerServie 接口
class CustomerServiceImpl implements CustomerService {
public void logout() {
System.out.println("Exit!");
}
}