多態的向上轉型與向下轉型

向上轉型當有子類對象賦值給一個父類引用時,多態自己就是向上轉型的過程java

父類引用指向子類對象spa

父類類型  變量名 = new 子類類型();

例如:Father father = new Son();//upcasting (向上轉型), 對象引用指向一個Son對象

向下轉型 一個已經向上轉型的子類對象能夠使用強制類型轉換的格式,將父類引用轉爲子類引用,這個過程是向下轉型,向下轉型必須以向上轉型爲前提。若是是直接建立父類對象,是沒法向下轉型的。code

子類引用指向父類對象,前提是已經進行了向上轉型對象

子類類型 變量名 = (子類類型) 父類類型的變量;

Son son = (Son) father;   //downcasting (向下轉型),father仍是指向Son對象

錯誤的狀況:編譯

Father f2 = new Father();

Son s2 = (Son) f2;//運行時出錯,子類引用不能指向父類對象

向上轉型與向下轉型的使用:ast

package com.day04;

/**
 * @author SFJ
 * @date 2019/11/10
 * @time 21:48
 **/
public class Test1 {
    public static void main(String[] args) {
        Person person = new Student();//向上轉型
        person.show();//調用子類重寫方法
        System.out.println(person.age);
        Student student = (Student)person;//向下轉型(前提是已經向上轉型)
        student.study();//調用子類特有方法
    }
}
class Person
{
    private String name = "Sangfengjiao";
    int age = 21;
    public void show()
    {
        System.out.println(name);
    }
}
class Student extends Person
{
    public String grade;
    int age = 22;
    public void show()
    {
        System.out.println("Studet:Sang fengjiao");
    }
    public  void study()
    {
        System.out.println("student should study");
    }
}

向上轉型的做用:能夠以父類做爲參數,使代碼變得簡潔class

package com.day04;

/**
 * @author SFJ
 * @date 2019/11/10
 * @time 22:04
 **/
public class Test2 {
    public static void main(String[] args) {
        doeat(new Male());
        doeat(new Female());
    }
    public static  void doeat(Human human)//向上轉型,子類對象做爲參數
    {
        human.eat();
    }
}
class Human{
    public void eat()
    {
        System.out.println("Human eat......");
    }
}
class Male extends Human{
    public void eat()
    {
        System.out.println("Male eat.....");
    }
}
class Female extends Human{
    public void eat()
    {
        System.out.println("Female eat......");
    }
}

轉型注意事項:變量

package com.day04;

/**
 * @author SFJ
 * @date 2019/11/10
 * @time 22:17
 **/
public class Test3 {
    public static void main(String[] args) {
        A a1 = new B();//向上轉型
        a1.methoda();//調用父類方法,沒有B類的方法,至關於父類對象
        B b1 = (B)a1;//向下轉型,前提已經向上轉型
        b1.methoda();//調用父類A方法
        b1.methodB();//調用B類方法
        b1.methodNew();
        A a2 = new A();
        B b2 = (B) a2; // 向下轉型,編譯無錯誤,運行時將出錯
        b2.methoda();
        b2.methodB();
        b2.methodNew();

    }

}
class A
{
    void methoda()
    {
        System.out.println("A method");
    }
}
class B extends A{
    void methodB()
    {
        System.out.println("B method");
    }
    void methodNew()
    {
        System.out.println("BNew method");
    }
}
相關文章
相關標籤/搜索