【发布时间】:2015-05-11 18:53:09
【问题描述】:
运行时多态与静态多态有何不同?
这可以是运行时多态的一个例子吗?
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();
}
}
代码选自here
【问题讨论】:
-
是的,这是运行时多态性的一个例子......和Difference is here
-
您可以在following answer 中看到另一个完整的 Java 示例。
-
Y obj1 = new X();这是不正确的,在运行时多态的情况下,您不能将父级转换为子级。
标签: java polymorphism