1 public class DemoClass4Interface {
2 public static void main(String[] args) {
3 //TODO interface 接口
4 /*
5 * 基本语法:interface 接口名称{ 规则属性,规则方法 }
6 * 接口其实是抽象的
7 * 规则的属性必须为固定值,而且不能修改
8 * 属性和行为的访问必须是公共的
9 * 属性应该是静态的
10 * 行为应该是抽象的
11 * 接口和类是两个层面的东西,同一层级
12 * 接口可以继承其他接口
13 * 类的对象需要遵循接口,在java中,这个遵循称之为:实现Implements,类需要实现接口,而且可以实现多个接口
14 * */
15 //1
16 Computer c = new Computer();
17 Phone p = new Phone();
18 c.typeC1 = p; //手机插到电脑的TypeC1接口上
19
20 //2
21 Phone p2 = new Phone();
22 c.typeC2 = p2; //手机插到电脑的TypeC2接口上
23 c.charging();
24
25 //上面1 2 结果如下:
26 /* 通过TypeC给电脑充电...
27 手机接受电脑,给其充电...
28 手机接受电脑,给其充电...*/
29 }
30 }
31
32 /*
33 * 举例:一个typeC接口,可以实现,充电和放电的作用,具体到电脑上,电脑就可以通过typeC实现充电和放电作用
34 * */
35
36 interface TypeC{
37
38 }
39
40 interface TypeCCharging extends TypeC{
41 //具体提供多大的充电电流不知道,所以这里定义需要抽象方法
42 public void charging();
43 }
44
45 interface TypeCReceCharging extends TypeC{
46 public void receCharging();
47 }
48
49 class Computer implements TypeCCharging{
50 public TypeCReceCharging typeC1;
51 public TypeCReceCharging typeC2;
52
53 public void charging() {
54 System.out.println("通过TypeC给电脑充电...");
55 typeC1.receCharging();
56 typeC2.receCharging();
57 }
58 }
59
60 class Phone implements TypeCReceCharging{
61 public void receCharging() {
62 System.out.println("手机接受电脑,给其充电...");
63 }
64 }