多态性的体现
- 方法的重载和重写
- 对象的多态性
对象的多态性
向上转型:程序自动完成
父类 父类对象 = 子类实例
向下转型:强制类型转换
子类 子类对象 = (子类)父类实例
栗子
package com.BigoSprite;
abstract class A{
public abstract void tell1();
public void tell2(){
System.out.println("A----tell2");
}
}
class B extends A{
public void tell1(){
System.out.println("B----tell1");
}
public void tell3(){
System.out.println("B---tell3");
}
}
public class BigoDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 向上转型
// A a =new B();
// a.tell1(); // tell1是重写的。。。输出 B----tell1
// a.tell2(); // 输出 A----tell2
// 向下转型,一定要先发生向上转型,才能发生向下转型
A a = new B();
B b = (B)a;
b.tell1(); // B----tell1
b.tell2(); // A----tell2
b.tell3(); // B---tell3
}
}