概述
(全文为Java描述)
本文将介绍 面对对象三大特征之一| 多态 |,并详细口语化描述 多态的由来 、使用 与 优劣势。
若本文风格符合你的胃口,请不要吝啬你的点赞和关注,这对我来说十分重要,谢谢!
如有疑问欢迎指出,发文旨在成就更好的你我~
一、什么是多态
同类型的对象,表现出不同形态
1,多态的表现形式
(大类型创建的小对象)
父类类型 对象名称 = 子类对象;
(new出来的这个)
2,多态的好处
使用父类类型作为参数,可以接受所有的子类对象
体现了多态的扩展性与便利性
二、多态的前提
1,有继承关系
2,有父类引用指向子类对象
3,有方法重写
三、多态的优劣
1,优势
在多态形式下,右边对象可以实现解耦合,便于扩展和维护
//业务逻辑发生改变时,后续代码无需修改,改改右侧new的子类就行
定义方法的时候,使用父类类型作为参数,可以接收所有子类对象
2,劣势
不能调用子类的特有功能(过不了编译时对父类的检查)
解决方案
1,直接创建子类实例,不使用多态
2,强转
已有Person p = new Student();
强转:Student s = (Student) p; //但不能转成别的子类
但怎么知道要合作项目中如何知道要转成什么子类呢?
强转判断:
if(p instanceof Student s){ //后加个变量名,直接实现 判断、转换 一步走
//判断条件格式:要转的实例 转换判断关键字 要转成的类型 转换后的实例名
上条件若是这个类型,true,能下到下面这的筛选语句
}else if(){
.....
}else{
sysout没有这个类型
}
四、代码演示
//父类1
public class Animal {
private int age;
private String color;
public Animal() {
}
public Animal(int age, String color) {
this.age = age;
this.color = color;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public void eat(String something) {
}
}
//父类1的子类1
public class Cat extends Animal {
public Cat() {
}
public Cat(int age, String color) {
super(age, color);
}
@Override
public void eat(String something) {
System.out.println("猫吃" + something);
}
public void catchMouse() {
System.out.println("猫猫只需要可爱就行了");
}
}
//父类1的子类2
public class Dog extends Animal {
public Dog() {
}
public Dog(int age, String color) {
super(age, color);
}
@Override
public void eat(String something) {
System.out.println("狗吃" + something);
}
public void lookHome() {
System.out.println("看家ing~");
}
}
//另外一个独立的类
public class Keeper {
private String name;
private int age;
public Keeper() {
}
public Keeper(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void keepPet(Animal a, String something) {
if (a instanceof Dog d) {
System.out.println("把" + something + "喂给狗");
d.eat(something);
} else if (a instanceof Cat c) {
System.out.println("把" + something + "喂给猫");
c.eat(something);
}
}
}
//测试类
public class test {
public static void main(String[] args) {
Animal a1 = new Dog(2, "white");
Animal a2 = new Cat(1, "yellow");
Keeper k = new Keeper();
k.keepPet(a1, "骨头");
k.keepPet(a2, "猫粮");
if (a1 instanceof Dog d) {
d.lookHome();
} else if (a1 instanceof Cat c) {
c.catchMouse();
}
if (a2 instanceof Dog d) {
d.lookHome();
} else if (a2 instanceof Cat c) {
c.catchMouse();
}
}
}
总结
本文将介绍 面对对象三大特征之一| 多态 |,并详细口语化描述 多态的由来 、使用 与 优劣势。
下篇博客将总结一些 面对对象中 常用的 基础思维与概念,敬请期待~~
若本文风格符合你的胃口,请不要吝啬你的点赞和关注,这对我来说十分重要,谢谢!
如有疑问欢迎指出,发文旨在成就更好的你我!