Java中的运行时多态性示例?

2022-01-24 00:00:00 polymorphism 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

相关文章