运行时多态性与静态多态性有何不同?
这可以是运行时多态的一个例子吗?
public class X
{
public void methodA() // Base class method
{
System.out.println ("hello, I'm methodA of class X");
}
}
public class Y extends X
{
public void methodA() // Derived Class method
{
System.out.println ("hello, I'm methodA of class Y");
}
}
public class Z
{
public static void main (String args []) {
X obj1 = new X(); // Reference and object X
X obj2 = new Y(); // X reference but Y object
obj1.methodA();
obj2.methodA();
}
}
Run Code Online (Sandbox Code Playgroud)
代码已从这里挑选出来
是的,这是Runtime polymorphismJava
在static polymorphism,编译器本身确定应该调用哪个方法.Method overloading是静态多态的一个例子.
在runtime polymorphism,编译器无法在编译时确定方法.Method overriding(作为你的例子)是一个例子runtime polymorphism.因为在Runtime polymorphism(作为你的例子)中,签名methodA()在类X(base class)和中都是相似的Y(child class).因此编译器无法在编译时确定应该执行的方法.只有在创建对象(运行时进程)之后,运行时环境才能理解要调用的确切方法.
这是因为,在这种情况下,obj1.methodA()呼叫methodA()在Class X因为obj1是对象的参考变量创建class X
AND
obj2.methodA()调用methodA(),Class Y因为obj2是为其创建的对象的引用变量class Y
| 归档时间: |
|
| 查看次数: |
16685 次 |
| 最近记录: |