这一章节我们来讨论一下接口。
之前我们已经聊过抽象类,他已经进行了第一步的抽象,把某些方法抽象出来,然后在子类那里实现,但他不是完全抽象。
而接口,就是进一步抽象,它里面全是没有实现的方法,所以的方法都在实现类里面实现。
1.概念
接口:就像类与类之间的一种协议,只需要知道某个类实现的某个接口, 那么,他就可以通过调用接口里面的方法来指向这个类的实现。
2.特性
(1)使用interface标注
(2)完全抽象
(3)属性域必须是public final static(这个是编译器自动转换的)
(4)方法必须是public
(5)向上转型,为父类指向子类对象提供途径,同时也使得java拥有多态这个特性
(6)不可以实例化
(7)接口可以多重实现
interface Instrument {
int id=0;
void Play();
}
3.实例
package com.ray.ch07;
public class Test {
public void tune(Instrument instrument) {
instrument.Play();
}
public void tune(Instrument[] instruments) {
for (int i = 0; i < instruments.length; i++) {
tune(instruments[i]);
}
}
public static void main(String[] args) {
Test test = new Test();
// Instrument instrument = new Instrument();//error
Instrument wind = new Wind();
Instrument bass = new Bass();
Instrument[] instruments = { wind, bass };
test.tune(instruments);
System.out.println(Instrument.id);// id是static
}
}
interface Instrument {
// private int id=0;//error
// private void Play();//error
int id = 0;
void Play();
}
class Wind implements Instrument {
@Override
public void Play() {
// id=2;//The final field Instrument.id cannot be assigned
System.out.println(id);
System.out.println("wind play");
}
}
class Bass implements Instrument {
@Override
public void Play() {
System.out.println("bass play");
}
}
输出:
0
wind play
bass play
0
从上面的代码可以看见:
1.接口是不可以new 的
2.子类必须实现接口的方法
3.通过向上转型,以Instrument为类型定义的wind和bass,也可以调用play方法,而且运行时自动识别应该绑定那个play方法
4.由于wind和bass必须重写play,因此play一定是public,因为wind和bass不是继承Instrument
5.我们通过打印Instrument里面的id,知道id一定是static,因为可以直接使用Instrument调用,而不需要new
6.通过在实现类wind里面修改id,就可以看到他的提示,提示id是final的。
7.接口的多重实现我们将在后面讲述。
总结:这一章节主要讨论了接口的概念、特性,以及举例来说明这些特性。
这一章节就到这里,谢谢。
-----------------------------------