Java学习 - 黑马(第二部分) - 随堂笔记 - 03_多态
1. 多态
1.1 多态概述
同一个对象,在不同时刻表现出来的不同形态
举例:猫
我们可以说猫是猫:猫 cat = new 猫();
我们也可以说猫是动物:动物 animal = new 猫();
这里猫在不同的时刻表现出来了不同的形态,这就是多态
多态的前提和体现
- 有继承/实现关系
- 有方法重写
- 有父类引用指向子类对象
1.2 多态中成药访问特点
- 成员变量:编译看左边,执行看左边
- 成员方法:编译看左边,执行看右边
为什么成员变量和成员方法的访问不一样呢?
- 因为成员方法有重写,而成员变量没有
package com.itheima_01;
public class Animal {
public int age = 4;
public void eat(){
System.out.println("动物吃东西。");
}
}
package com.itheima_01;
public class Cat extends Animal{
public int age = 2;
public int weight = 10;
@Override
public void eat() {
System.out.println("猫吃鱼。");
}
public void playGame(){
System.out.println("猫捉迷藏。");
}
}
package com.itheima_01;
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;//报错
}
}
1.3 多态的好处和弊端
- 多态的好处:提高了程序的扩展性
- 具体体现:定义方法的时候,使用父类型作为参数,将来在使用的时候,使用具体的子类型参与操作
- 多态的弊端:不能使用子类的特有功能
package com.itheima_02;
public class Animal {
public void eat(){
System.out.println("动物吃东西。");
}
}