目录
Java接口的多态特性
1.多态参数
-
接口的引用指向了实现了接口的类的对象
public class Parameter {
public static void main(String[] args) {
//接口类型的变量 if01 可以指向实现了IF接口的类的对象实例
IF if01 = new Monster();
if01 = new Car();
}
}
interface IF {}
class Monster implements IF {}
class Car implements IF {}
Usb接口案例
public class Interface01 {
public static void main(String[] args) {
Phone phone = new Phone();
Camera camera = new Camera();
Computer computer = new Computer();
computer.work(phone);
computer.work(camera);
}
}
public interface Usb {
//规范
public void start();
public void stop();
}
public class Phone implements Usb {
@Override
public void start() {
System.out.println("手机开始工作");
}
@Override
public void stop() {
System.out.println("手机停止工作");
}
}
public class Camera implements Usb{
@Override
public void start() {
System.out.println("相机开始了工作");
}
@Override
public void stop() {
System.out.println("相机停止了工作");
}
}
public class Computer {
//编写一个方法,计算机工作
//Usb usb 形参是接口类型 Usb
//接口的引用可以指向(接收)实现了接口的类的对象
public void work(Usb usb) {
//通过接口来调用方法
usb.start();
usb.stop();
}
}
2.多态数组
-
接口的引用不能直接调用实现类中特有的成员,需要向下转型后进行调用。
-
类似于父类的引用不能调用子类中特有的成员。
package test.Demo09;
public class Abc {
public static void main(String[] args) {
//多态数组 -> 接口类型数组
Usb[] usb = new Usb[2];
usb[0] = new Phone();
usb[1] = new Camera();
for (int i = 0; i <usb.length ; i++) {
usb[i].work(); //动态绑定
if (usb[i] instanceof Phone) { //判断usb[i]的运行类型是否是 Phone
//需要向下转型,因为接口的引用不能直接调用实现类中特有的成员
((Phone)usb[i]).call();
}
}
}
}
interface Usb {
void work();
}
class Phone implements Usb{
public void call() {
System.out.println("手机可以打电话");
}
@Override
public void work() {
System.out.println("收集工作中");
}
}
class Camera implements Usb{
@Override
public void work() {
System.out.println("相机工作中");
}
}
3.接口的多态传递现象
public class Pass {
public static void main(String[] args) {
//接口类型的变量可以指向实现了该接口的类的对象
IG ig = new Teacher();
//如果IG继承了IH接口,而Teacher类实现了IG接口
//那么,实际上就相当于Teacher 类也实现了IH接口
IH ih = new Teacher();
}
}
interface IH {}
interface IG extends IH{}
class Teacher implements IG{}