MENU

多态性

June 5, 2018 • Read: 2436 • Java阅读设置

  1. 多态性的体现:方法的重载与重写、对象的多态性
  2. 对象的多态性:

    1. 向上转型:程序自动完成 Father f = Son()
    2. 向下转型:强制类型转船 Son s = (Son)Father() 注意:向下转型必须先向上转型在向下转型
class A{
    public void tell1(){
        System.out.println("A--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 static void main(String args[]){
    //向上转型
//    B b = new B();
//    A a = b;
//    a.tell1();//B--tell1
//    a.tell2();//A--tell2
    //向下转型
    A a = new B();//先上转型,实例化B
    B b = (B)a;//再向下转型
    b.tell1();//B--tell1
    b.tell2();//A--tell2
    b.tell3();//B--tell3
}
Last Modified: February 8, 2020
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment