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中的运行时多态性示例?
基础教程推荐
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01