运行时多态 [英] Runtime polymorphism

查看:65
本文介绍了运行时多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有A类

public class A
{
    public void method()
    {
        //do stuff
    }
}

还有另一个B类

public class B extends A
{
    public void method()
    {
        //do other stuff
    }
}

现在我有以下陈述:

A a = new B();
a.method();

这是运行时多态性的一个例子吗?如果是,那么在编译时是否不对引用a进行绑定?

Is this an example of run time polymorphism? If yes, then is no binding is done for the reference a at compile time?

推荐答案

编译器将告诉您这是行不通的,因为A和B之间没有关系可以让您编写A a = new B();

B要么必须扩展A,要么都必须实现其中带有void method()的通用接口.

B either has to extend A or both have to implement a common interface with void method() in it.

您可以通过在编译器中尝试快速地回答此问题.成为实验者-比论坛快.

You could have answered this very quickly by trying it with the compiler. Be an experimentalist - it's faster than forums.

更新:

现在,它有效,因为B扩展了A.您关心的绑定(动态绑定)是在运行时完成的.变量"a"的静态编译时间类型为A类;在运行时,它动态绑定到B类型的引用.是的,我认为这是多态的一个例子.

It works, now that B extends A. The binding that you care about, dynamic binding, is done at runtime. The static compile time type for the variable "a" is class A; at runtime it is dynamically bound to a reference of type B. Yes, I would consider this to be an example of polymorphism.

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

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