Java中运行时多态的示例? [英] Example of Runtime polymorphism in Java?

查看:129
本文介绍了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中的运行时多态性

静态多态性,编译器本身决定应该调用哪个方法。 方法重载是静态多态的一个例子。

In static polymorphism, compiler itself determines which method should call. Method overloading is an example of static polymorphism.

运行时多态性,编译器无法在编译时确定方法。 方法覆盖(作为示例)是运行时多态性的示例。
因为在运行时多态性(作为你的例子), methodA()的签名在两者中都是相似的类 X(基类) 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 是为类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

AND
obj2.methodA() methodA() > Y类因为 obj2 是为类Y创建的对象的引用变量

AND obj2.methodA() calls methodA() in Class Y since obj2 is reference variable of object created for class Y

这篇关于Java中运行时多态的示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆