what's the difference between inheritance and polymorphism?

前端 未结 8 1755
[愿得一人]
[愿得一人] 2020-12-05 05:08

can you give me a simple example of inheritance and polymorphism, so it could be fully clear and understandable?

using C# would make it more clear, as I already lear

相关标签:
8条回答
  • 2020-12-05 06:05

    Inheritance means that if you create a class Car with a public field TankSize then you derive from it a class SuperCar the last one has inherited the field TankSize from Car.

    Polymorphism is the fact that every time in the code you have a method where a Car is expected you can pass a SuperCar and it will behave like a Car.

    With virtual methods defined as needed you will be calling a method on a base class but the actual object on which you are working on will execute its version of the virtual method so you will be calling SuperCar.GetPrice and not Car.GetPrice in fact.

    This in few words, for more, I see the others are already answering as I write.

    0 讨论(0)
  • 2020-12-05 06:07

    There isn't difference between inheritance and polymorphism. Polymorphism is a PART OF inheritance and it can not exists without it. In the short words, polymorphism is a ability to treat object as a object of base class, but calling the VIRTUAL method on the base class will invoke apropriate method from child class. Good example is here: http://www.psworld.pl/Programming/Inheritance

    0 讨论(0)
提交回复
热议问题