简体   繁体   中英

Is it a compile time polymorphism or runtime?

如果我们在不使用超类的引用变量的情况下调用子类的重写方法,那将是运行时多态吗?

Yes, it would. Java objects "decide" which version of a method to call based on the type of the value at runtime, not the value of the variable at compile time.

Consider the following classes:

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

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

All of the following invocations to foo() will return "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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM