1.基本介绍
- 接口就是给出一些没有实现的方法,到某个类使用的时候,在根据具体情况吧这些方法写出来
- 在jdk7.0前,接口里的所有方法偶没有方法体,即都是抽象方法
- jdk8.0以后,接口可以有静态方法、默认方法,也就是说的接口中可以有方法的具体实现
2.注意事项和细节
- 接口不能被实例化
- 接口中所有的方法都是public方法,接口中的抽象方法,可以不用abstract修饰
- 一个普通类实现接口,就必须将接口中的所有方法都实现
- 抽象类实现接口, 可以不实现接口方法
- 一个类可以实现多个接口,例:class A implements B, C {}
- 接口中的属性只能是final的,而且是 public static final 修饰, 必须初始化。比如 int a = 1; 实际上是: public static final int a = 1;
- 接口可以直接访问讲台属性: 接口名.属性名
- 接口不能继承其他类,但是可以集成其他接口
- 接口的访问修饰符只能是public和默认,这点和类的修饰符一样
- 在java中,实现接口可以理解为是最类的单一继承机制的一种补充
3.实现接口vs继承类
- 接口和集成解决的问题不同:
继承的主要价值在于: 解决代码复用性和可维护性
接口的主要加载在于: 设计,设计好各种规范(方法),让其他类去实现这些方法
- 接口比继承更加灵活,继承满足的是is-a的关系,接口实现只需满足like-a的关系
- 接口在一定程度上实现了代码解耦
4.接口的多态
- 多态参数
class Computer {
// UsbInterface usbInterface 形参是接口类型 UsbInterface
public void work(UsbInterface usbInterface) {
usbInterface.start();
}
}
class Phone implements UsbInterface {
public void start() {
System.out.println("Phone start work...");
}
}
interface UsbInterface {
public void start();
}
class TextComputer {
public static void main(String[] args) {
Phone phone = new Phone();
Computer computer = new Computer();
computer.work(phone);
}
}
- 多态数组
class Phone implements UsbInterface {
public void call() {
System.out.println("Phone Phone...");
}
}
class Camera implements UsbInterface {
public void photoGraph() {
System.out.println("Camera photograph...");
}
}
interface UsbInterface {
}
class TextComputer {
public static void main(String[] args) {
UsbInterface[] usbInterfaces = new UsbInterface[2];
usbInterfaces[0] = new Phone();
usbInterfaces[1] = new Camera();
for (int i = 0; i < usbInterfaces.length; i++) {
if (usbInterfaces[i] instanceof Camera) {
// 向下转型
((Camera) usbInterfaces[i]).photoGraph();
}
if (usbInterfaces[i] instanceof Phone) {
((Phone) usbInterfaces[i]).call();
}
}
}
}
- 接口存在多态传递现象
interface IH {}
interface IG extends IH {}
class Teacher implements IG {}
public class PolyPass {
public static void main(String[] args) {
// 接口类型的变量可以指向实现了该接口的类的最想实例
IG ig = new Teacher();
// 如果IG集成了IH,而Teacher实现了IG接口
// 那么, 实际就相当于Teacher也实现了IH接口
// 这就是接口多态传递现象
IH ih = new Teacher();
}
}