繁体   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