关于动态多态性 [英] About Dynamic Polymorphism

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

问题描述

Hi EveryOne,



我有以下问题。



Hi EveryOne,

I had following question.

Class A{
public void Test(){
System.out.println("In A Class Test Method");
}
}

Class B extends A{
public void Test(){
System.out.println("In B Class Test Method");
}
}
Class MainMethod{
public static void main(String [] args){
A a = new B();
 a.Test();//This will call the B class Test Method
}
}
}





在上面的示例中,这是一个动态多态的情况,该方法是调用由创建的对象决定(在上面的情况下,B类测试方法将被调用,因为我创建了B类对象)。现在我想调用A类的方法而不对代码进行任何更改。是否可能?如果不是那怎么可以说是动态多态,因为通过看到创建的对象,我们可以轻松地说B类测试方法将被称为



谢谢



In the above example which is a dynamic polymorphism case the method to be called is decided by the object created(in above case B Class Test Method will be called since I create B Class Object).Now I want to call the method of A Class without making any changes to the code.Is it possible?If not then how it can be said to be dynamic polymorphism as by seeing the object created we can easily say tha B Class Test Method wil be called

Thanks

推荐答案

首先你要了解动态多态的含义。应该在运行时确定Object的行为。在你的代码中,仅通过观察以下行,

first of all you have to understand the meaning of dynamic polymorphism. The behaviour of the Object should be determined at runtime. In your code , by only watching the following line ,
a.test();

,无法预测哪种方法可以叫做。但是根据你的简单例子,你可以很容易地说它可能会调用Class B的test()方法,但在大型场景中可以考虑一下。假设A类有很多子类,比如B类,C类,...... N类,有一种类似的方法:



, one can''t predict which method can be called. However as per your simple example , you can easily say that it might call Class B''s test() method , But think it little bit in large scenario. Suppose Class A has lots of sub classes,say Class B, Class C, .. Class N and there is a method something like :

public void getResult(A object){
  //some code
  object.test();//say line no 3
  //some code
}







在这个例子中你能说出哪个测试应该调用()方法。所以没有人可以预测。

这只能在运行时确定。




In this example can you able to say which test() method should be called. So no body can predict.
This can only be determined at runtime.


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

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