在抽象类中调用重写的函数
所以我有抽象类Worker
,它具有抽象函数computePay
。
该类的两个子类是 HourlyWorker
和 FixedWorker
, 现在我已经在这两个类中提供了computePay的实现。
Worker[] w=new worker[2];
w[0]=new HourlyWorker;
w[1]=new FixedWorker;
现在,当我说w[0].computePay
时,我的代码会说我如何确定调用了哪个computePay , 我知道会调用子类中的那个,但是哪一个呢?
IE 如果我的两个子类都有不同的computePay函数实现, 下面的代码会给我想要的结果吗?
w[0].computePay //Prints the pay as per the implementation in HourlyWorker;
w[1].computePay //Prints the pay as per the implementation in FixedWorker;
我还听说过运算符/关键字的实例
,但我不知道它在这里有什么用吗?
So i have the abstract class Worker
, which has the abstract function computePay
.
The two children classes of this class are HourlyWorker
and FixedWorker
,
now i have provided the implementation of computePay
in both these classes.Now my code says
Worker[] w=new worker[2];
w[0]=new HourlyWorker;
w[1]=new FixedWorker;
now when i say w[0].computePay
how am i sure that which computePay is called,
i know the one from the child class will be called, but which one?
i.e.
If my both the child classes have different implementation of the computePay
function,
will the following code give me the desired result?
w[0].computePay //Prints the pay as per the implementation in HourlyWorker;
w[1].computePay //Prints the pay as per the implementation in FixedWorker;
Also i heard about the instance of
operator/keyword, but i dont know will it be of any use here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,Java 将确保调用“正确”的方法。
无需使用instanceof手动调度。
OOP 的基本概念是您不需要知道的。您正在对抽象类中定义的接口进行编程,并且不需要知道此处使用的是哪个实现(或者它的作用)。
Yes, Java will make sure that the "correct" method gets called.
No need for manual dispatch using instanceof.
A basic concept of OOP is that you don't need to know. You are programming to the interface defined in your abstract class, and don't need to know about which implementation is being used here (or what it does).
对象的实际类型之一。因此,如果您的对象是一个
HourlyWorker
(使用new HourlyWorker()
初始化),您将调用computePay
方法这种类型。instance of
关键字用于测试对象是否属于指定类型。它不应该用在好的设计中(除非重写equals
)。在这里是没有用的。相反,您应该按照您的建议依赖多态性。The one of the actual type of your object. So if your object is a
HourlyWorker
(initialized withnew HourlyWorker()
) you will call thecomputePay
method of this type.The
instance of
keyword is used to test if an object is of a specified type. It should not be used in good designs (except when overridingequals
). It is of no use here. On the contrary, you should rely on the polymorphism as you suggested.java中的方法默认是虚拟的(就像在CPP中你必须使用virtual关键字),所以java将确保方法是根据对象而不是引用来调用的。抽象方法是C++的纯虚函数
还要注意instanceof在这里不会有用,所以避免它。
The methods in java are by default virtual(like in CPP you have to use virtual keyword), so java will make sure the methods are called in respect of object rather than the reference. Abstract method are pure virtual function of C++
Also note that instanceof wont be useful here, so avoid it.