簡體   English   中英

它是編譯時多態性還是運行時?

[英]Is it a compile time polymorphism or runtime?

如果我們在不使用超類的引用變量的情況下調用子類的重寫方法,那將是運行時多態嗎?

是的,會的。 Java對象根據運行時值的類型(而不是編譯時變量的值)來“決定”要調用的方法版本。

考慮以下類別:

public class A {
    public String foo() {
        return "A";
    }
}

public class B extends A {
    public String foo() {
        return "B";
    }
}

以下對foo()所有調用將返回"B"

// compile-time type is A, runtime type is B
A a=new B();
a.foo();

// compile-time type is B, runtime type is B
B b=new B();
b.foo();

// compile-time type is B, runtime type is B
new B().foo();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM