为什么我们应该重写方法? [英] Why should we override a method?

查看:271
本文介绍了为什么我们应该重写方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近有人问我这个问题:为什么要覆盖一个方法?"

Recently I was asked this question "why should one override a method? "

我回答,如果我有一个包含10个方法的类,并且我想使用除一个方法之外的所有功能,那么我将覆盖该方法以具有自己的功能.

I replied, if I have a class with 10 methods and I want to use all of its functionality except one method, then I will override that method to have my own functionality.

然后,在这种情况下,面试官回答了为什么我们不能编写一个具有不同名称的新方法,而改用该方法.

Then the interviewer replied in that case why cant we write a new method with a different name and use that method instead.

是的,这也是正确的.现在我很困惑.重写方法的真正目的是什么?

Yes this is also right. Now I am confused. What is the real objective in overriding a method?

有人可以告诉我吗?谢谢大家.

Can anyone please tell me? Thank you all in advance.

推荐答案

如果要在派生类中为该方法赋予其他名称,则无法使用相同的接口调用它.您始终可以通过基类指针调用它.

If you will give another name to the method in derived class, you cant invoke it with same interface. You can always invoke it through base class pointer.

Base p = new Derived();
p.overrideMethod();

如果Derived类是从Base派生的,则它将自动调用派生版本,而不是Base的派生版本.如果名称不同,则不可能.它被称为针对接口而非实现的代码.

If Derived class is derived from Base then it will automatically call the derived version and not of Base. In case of different name, it is not possible. It is called code against interfaces and not implementations.

这篇关于为什么我们应该重写方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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