1、类的多态
理解:子类对象指向父类引用
父类引用中存储的是子类对象在堆中开辟的内存地址
前提:必须是父子类关系
比如:Vehicles v = new Plane();//0x001好处:需求升级时不违反OCP
设计原则:前人给我们总结的经验,告诉我们什么不能干
设计模式:前人给我们总结的经验,告诉我们怎么做
OCP - 开闭原则
O - Open - 在项目迭代时,对于创建类是欢迎的
C - Close - 在项目迭代时,修改原有类是拒绝的
P - principle - 原则
需求升级/迭代:自行车 -> 汽车 -> 飞机
步骤:
创建Plane类,继承Vehicles类,重写start、stop方法
public abstract class Vehicles {
public abstract void start();
public abstract void stop();
}
//创建Plane类,继承Vehicles类
public class Plane extends Vehicles{
//重写start、stop方法
@Override
public void start() {
System.out.println("飞机:飞");
}
@Override
public void stop() {
System.out.println("飞机:到达p城,跳伞");
}
public class Test01 {
public static void main(String[] args) {
Teacher t = new Teacher();
//类的多态:子类对象指向父类引用
//父类引用中存储的是子类对象在堆中开辟的内存地址
//前提:必须是父子类关系(Vehicles与Plane是父子关系)
Vehicles v = new Plane();//0x001
t.open(v);
System.out.println("欣赏沿途的风景...");
t.close(v);
}
2、接口的多态
接口的多态:实现类对象指向接口的引用 接口的引用中存储的是实现类对象在堆中开辟的内存地址 前提:必须是实现关系( Disk实现IUSB)
需求:模拟电脑连接外部设备
需求升级:鼠标-硬盘-键盘
public static void main(String[] args) { Computer computer = new Computer(); //接口的多态:实现类对象指向接口的引用 //接口的引用中存储的是实现类对象在堆中开辟的内存地址 //前提:必须是实现关系( Disk实现IUSB) IUSB usb = new KeyBoard(); computer.connection(usb); }
//前提:必须是实现关系( Disk实现IUSB) public class KeyBoard implements IUSB{ @Override public void use() { System.out.println("键盘:输入数据"); }
public interface IUSB { public void use(); }
public class Computer { public void connection(IUSB usb){ usb.use(); } }