【381-383】内部类
2022-01-20 20:32:00 # JavaSE

内部类概述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class _381_内部类概述 {

}

class Test01{
// 静态内部类
static class Inner1{

}

// 实例内部类
class Inner2{

}

public void doSoming(){
// 局部内部类
class Inner3{

}
}
}

匿名内部类

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
33
34
public class _382_引出匿名内部类 {
public static void main(String[] args) {
MyMath myMath = new MyMath();
// 多态
myMath.mySum(new ComputeImpl(), 1, 2);
// 使用匿名内部类
// new 接口,{}后是对接口的实现,该实现的类没有名字
myMath.mySum(new Compute() {
@Override
public int sum(int a, int b) {
return a+b;
}
}, 1, 2);
}
}

interface Compute{
int sum(int a, int b);
}

class ComputeImpl implements Compute{
@Override
public int sum(int a, int b) {
return a+b;
}
}

class MyMath{
public void mySum(Compute c, int x, int y){
int res = c.sum(x, y);
System.out.println(x + "+" + y + "=" + res);
}
}

Prev
2022-01-20 20:32:00 # JavaSE
Next