What are the problems that can arise in an implementation that lacks polymorphism?

StackOverflow https://stackoverflow.com/questions/23688844

  •  23-07-2023
  •  | 
  •  

Вопрос

I understand what polymorphism means but I'm having difficulty understanding the problems that arise if it isn't used. Could someone explain it to me?

Это было полезно?

Решение

The basic concept is code re-use. Polymorphism is achieved in .NET via interfaces and abstract/base classes. Say you have a Cat class that has a Speak() method which outputs "MEOW!" and say that you use this class all over your application as type Cat. Now, if one day you need to replace all cats with Dogs using a Dog class who has a Speak() method which outputs "WOOF!" you're going to have a lot of manual work to do to replace all instances of Cat with Dog. And what if you need a method that can let a Cat or Dog speak? Then you need a lot of copy-paste boiler-plate redundant code.

Imagine instead that you code Cat : ISpeak and Dog : ISpeak where ISpeak is an interface which exposes the Speak() method. Now you have no rework to do at all and can happily switch between Cat, Dog, and other things that can speak, as long as you use the interface type for all type declarations.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top