2014-01-07 43 views
0

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

+1

多态性是,根据定义,运行时间概念。 –

+0

是的。请参阅下面的完整说明。 http://stackoverflow.com/questions/8355912/overloading-is-compile-time-polymorphism-really – Kabron

+1

@SotiriosDelimanolis在Java世界中,是的,但不是一般的。我们Java人称之为多态的实际上只是一种多态。 – yshavit

回答

0

是的,它会。 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(); 
相关问题