多态
一、多态的概述
我们要学习多态首先我们要知道多态是什么。
多态是同一个对象,在不同时刻表现出来的不同形态。
多态的前提
- 要有继承或实现关系
- 要有方法的重写
- 要有父类引用指向子类对象
二、多态的好处和弊端
好处: 提高程序的扩展性。定义方法时候,使用父类型作为参数,在使用的时候,使用具体的子类型参与操作。
弊端: 不能使用子类的特有成员
三、成员访问特点
成员访问特点
-
成员变量
编译看父类,运行看父类
-
成员方法
编译看父类,运行看子类
示例代码:
//动物类
public class Animal {
public int age = 40;
public void eat() {
System.out.println("动物吃东西");
}
}
//猫类
public class Cat extends Animal {
public int age = 20;
public int weight = 10;
@Override
public void eat() {
System.out.println("猫吃鱼");
}
public void playGame() {
System.out.println("猫捉迷藏");
}
}
//测试类
public class AnimalDemo {
public static void main(String[] args) {
//有父类引用指向子类对象
Animal a = new Cat();
System.out.println(a.age);
// System.out.println(a.weight);
a.eat();
// a.playGame();
}
}
四、多态中的转型
-
向上转型
父类引用指向子类对象就是向上转型
-
向下转型
格式:子类型 对象名 = (子类型)父类引用;
示例代码:
//动物类
public class Animal {
public void eat() {
System.out.println("动物吃东西");
}
}
//猫类
public class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫吃鱼");
}
public void playGame() {
System.out.println("猫捉迷藏");
}
}
//测试类
public class AnimalDemo {
public static void main(String[] args) {
//多态
//向上转型
Animal a = new Cat();
a.eat();
// a.playGame();
//向下转型
Cat c = (Cat)a;
c.eat();
c.playGame();
}
}
总结: 我们要使用多态进行编程那就一定要先满足多态的前提,了解多态的成员访问特点,那样才能更好的运用多态。