Example of Runtime polymorphism in Java?(Java中的运行时多态性示例?)
问题描述
运行时多态与静态多态有何不同?
How is Runtime polymorphism different from Static polymorphism ?
这可以是运行时多态的一个例子吗?
Can this be an example of Runtime polymorphism ?
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();
}
}
代码选自这里
推荐答案
是的,这是 Java 中的 Runtime polymorphism
Yes this is Runtime polymorphism
in Java
在静态多态
中,编译器自己决定应该调用哪个方法.方法重载
是静态多态的一个例子.
In static polymorphism
, compiler itself determines which method should call. Method overloading
is an example of static polymorphism.
在运行时多态
中,编译器无法在编译时确定方法.Method overriding
(作为你的例子)是 runtime polymorphism
的一个例子.因为在 Runtime polymorphism
(作为您的示例)中, methodA()
的签名在类 X(base class)
和 中都是相似的代码>Y(子类)
.因此编译器无法在编译时确定应该执行的方法.只有在对象创建(这是一个运行时过程)之后,运行时环境才知道要调用的确切方法.
In runtime polymorphism
, compiler cannot determine the method at compile time. Method overriding
(as your example) is an example of runtime polymorphism
.
Because in Runtime polymorphism
(as your example), the signature of methodA()
is similar in both the class X(base class)
and Y(child class)
. So compiler cannot determine method at compile time which should execute.
Only after object creation(which is a run time process), the runtime environment understand the exact method to call.
因为在这种情况下,obj1.methodA()
在Class X
中调用methodA()
,因为obj1
是为 class X
It is because of that in this case, obj1.methodA()
calls methodA()
in Class X
since obj1
is reference variable of object created for class X
与obj2.methodA()
在 Class Y
中调用 methodA()
因为 obj2
是为 <代码>Y类
AND
obj2.methodA()
calls methodA()
in Class Y
since obj2
is reference variable of object created for class Y
这篇关于Java中的运行时多态性示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java中的运行时多态性示例?


- 转换 ldap 日期 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 获取数字的最后一位 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01