多态是同一个对象,在不同时刻表现出不同的形态
前提和体现:
有继承/(实现)关系
有方法重写
有父类引用指向子类对象,如People p=new Student();
一,多态中成员访问特点
成员变量:编译时编译的是左边父类,所以访问的也是父类成员变量的值
成员方法:编译时编译的是左边父类,所以访问父类没有的方法会报错,但是执行时执行的是子类重写后的方法
二,优缺点
优点:定义方法的时候,使用父类作为参数,将来在使用的时候,使用子类类型参与操作,提高了程序的拓展性
缺点:不能使用子类的特有功能
三,多态的转型
向上转型:从父类引用指向子类对象People p=new Student();
向下转型:从父类引用转为子类对象People p=new Student();无法访问Student特有的方法,所以可以Student p1=(Student)p;这样就能克服不能使用子类特有的功能这一缺点了
最后做了一个练习加深印象
animial类(父类)
public class Animial {
public int age;
public int weight;
public void eat(){
System.out.println("动物正在进食...");
}
}
cat,dog类(子类)
public class Cat extends Animial{
@Override
public void eat(){
System.out.println("猫在吃鱼...");
}
public void play(){
System.out.println("猫在玩耍...");
}
}
public class Dog extends Animial{
@Override
public void eat() {
System.out.println("狗在啃骨头...");
}
public void watch(){
System.out.println("狗在看门...");
}
}
animialeat类
public class AnimialEat {
public void active(Animial a){
a.eat();
}
}
test类
public class Test {
public static void main(String[] args) {
Animial c=new Cat();
c.eat();
// 这种状态下无法调用cat类独有的方法
// c.play();
System.out.println("--------------------");
// 向下转型后可以使用
Cat cc=(Cat)c;
cc.eat();
cc.play();
System.out.println("--------------------");
Cat ccc=new Cat();
Dog dd=new Dog();
AnimialEat ae=new AnimialEat();
ae.active(ccc);
ae.active(dd);
}
}
运行结果是



