1 接口可以使用多态
//定义一个Animal接口
public interface Animal {
//抽象方法move()
void move();
}
//Cat类实现接口Animal
class Cat implements Animal {
//覆盖move()方法
public void move() {
System.out.println("猫在走猫步");
}
}
//Bird类实现接口Animal
class Bird implements Animal {
//覆盖move()方法
public void move() {
System.out.println("鸟在飞翔");
}
}
//测试类
class AnimalTest {
public static void main(String[] args) {
//接口Animal使用多态
Animal a = new Cat();
a.move();
Animal b = new Bird();
b.move();
}
}
运行结果:
![image-20210809112147967](https://i.loli.net/2021/08/09/cCpL2eADZI7irWE.png)
2 接口之间也可以强制类型转换,没有继承关系,可以强转,但是运行时可能会出现ClassCastException异常
public class InterfaceTest04 {
public static void main(String[] args) {
//接口使用多态
K k1 = new N();
k1.testK();
//接口之间强转
M m = new N();
K k2 = (K) m;
}
}
interface K {
void testK();
}
interface M {
void testM();
}
class N implements K, M {
@Override
public void testK() {
}
@Override
public void testM() {
}
}
3 继承和实现可以同时存在
extends关键字在前,implements关键字在后。
接口通常提取的是行为动作。
public class InterfaceTest01 {
public static void main(String[] args) {
//创建对象
Magic magic = new ADC();//多态
magic.cap();
Tank tank = new Tank();
tank.protect();
}
}
//法术装备接口
interface Magic {
//大法帽方法
void cap();
}
//英雄类
class Hero {
}
//ADC类英雄继承英雄类,实现法术装备接口
class ADC extends Hero implements Magic {
@Override
public void cap() {
System.out.println("我是ADC,出了一件大法帽");
}
}
//Tank类继承英雄类,Tank类英雄不出法术装备,可以不实现接口
class Tank extends Hero {
public void protect() {
System.out.println("我是Tank,我的职责是保护队友");
}
}
运行结果:
![image-20210809112352283](https://i.loli.net/2021/08/09/xKZJy71hdeiBzU9.png)
4 接口在开发中的作用
接口在开发中的作用,类似于多态在开发中的作用。
多态在程序中的作用:
降低程序耦合度,提高程序扩展力。
接口在开发中的作用:
接口是完全抽象的,正好符合编程要求,面向抽象编程。
接口的使用离不开多态机制,两者配合,降低程序耦合度。