Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should we override a method? [duplicate]

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

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.

like image 804
Krishna Chaitanya Avatar asked Sep 19 '25 01:09

Krishna Chaitanya


2 Answers

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.

i.e.

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

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.

like image 180
Apurv Avatar answered Sep 20 '25 14:09

Apurv


.

why cant we write a new method with a different name and use that method instead

It is because we want to use polymorphism. You could tell the interviewer this example: There is a module that calls specific methods on objects you give it; now imagine you can't change that module (e.g. no source). You can't tell it to use a different method but you can give it an object of a subclass which has overridden that method. To the module it will appear that nothing changed.

In practice it is also often the case that you could change that module but dont want to.

like image 21
Bernd Elkemann Avatar answered Sep 20 '25 13:09

Bernd Elkemann