Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between inheritance and polymorphism?

Tags:

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 learned it.

P.S: the tutors, books we've got are in native language, (arabic)

sorry if that question seemed so easy, even silly on you guys, but these concepts are considered hard; if you don't fully understand them, then you fail.

like image 278
Obzajd Avatar asked Sep 06 '11 20:09

Obzajd


2 Answers

This is polymorphism:

public interface Animal 
{
  string Name { get; }
}

public class Dog : Animal
{
  public string Name { get { return "Dog"; } }
}

public class Cat : Animal
{
  public string Name { get { return "Cat"; } }
}

public class Test 
{
  static void Main()
  {
      // Polymorphism
      Animal animal = new Dog();

      Animal animalTwo = new Cat();

      Console.WriteLine(animal.Name);
      Console.WriteLine(animalTwo.Name);
  }
}

this is Inheritance:

public class BaseClass
    {
        public string HelloMessage = "Hello, World!";
    }

    public class SubClass : BaseClass
    {
        public string ArbitraryMessage = "Uh, Hi!";
    }

    public class Test
    {
        static void Main()
        {
            SubClass subClass = new SubClass();

            // Inheritence
            Console.WriteLine(subClass.HelloMessage);
        }
    }
like image 59
Russ Clarke Avatar answered Oct 08 '22 22:10

Russ Clarke


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.

like image 27
Davide Piras Avatar answered Oct 08 '22 23:10

Davide Piras