0

In an interview it was asked why do we need to override method of base class. I tried to answer like when we want to have different implementation in derived class. But then he said, "Why don't we just create a new method with different name and different implementation instead of overriding base class method?", anyway we are not reusing base class method as implementation will be different then just create a new method instead of overriding.

I got confused what to answer. Could somebody explain.

public class BaseClass { virtual void Foo(){} } public class DerivedClass: BaseClass { override void Foo(){} } 

Generally we implement overriding like above. What he said is like why do we need concept of overriding we can do like below

public class BaseClass { void Foo(){} } public class DerivedClass: BaseClass { void Foo1(){} } 

His question was looking weird I tried to explain but like its a method of base class we are just redefining it in derived class. In this way our code will be clean as well. But looks like he was not satisfied.

7
  • Consider: Animal a = new Dog(); Animal b = new Cat(); a.Speak(); b.Speak(); - how is it different to Dog a = new Dog(); Cat a = new Cat(); a.Speak(); b.Speak();? Commented Nov 29, 2018 at 5:12
  • 1
    Do you want to change the "base" functionality or implement new functionality? Overriding the method comes back to the bases of polymorphism, where you could then pass an instance of the "new" class to methods requiring instances of the "old" and they would be able to interact with the new functionality provided by it Commented Nov 29, 2018 at 5:13
  • 1
    What does it mean to “program to an interface”? Commented Nov 29, 2018 at 5:21
  • 1
    Liskov Substitution Principle Commented Nov 29, 2018 at 5:25
  • 1
    I strongly suspect that Foo1 should be Foo to show shadowing vs. virtual methods... So far the post is way too broad - hopefully it somewhat covered by 3 duplicates I selected. Commented Nov 29, 2018 at 5:40

1 Answer 1

0

I would check this answer: Why does this polymorphic C# code print what it does?

then try to grasp the concept of methods in an object basically having pointers to code. When you override implementation in an subclass then that becomes the new code pointed to, whether it's used or cast as a superclass or not.

So the main purpose of overriding is to create classes that inherit from one class but each have their own implementation and then be able to treat or operate on them equally the same as the original superclass. This is the essence of the Liskov Principle or the 'L' in SOLID. What is an example of the Liskov Substitution Principle?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.