19

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.

Obzajd
  • 283
  • 1
  • 2
  • 8
  • 41
    Guys, the poster is clearly not a native English speaker, and he's asking us to help him understand the difference between two English words that are used heavily in programming since his textbooks are written in Arabic. Since he doesn't know English that well, he's hoping that a code snippet in a language he does understand will help him get the gist without having to read several paragraphs of explanations in English. Give him a break. – StriplingWarrior Sep 06 '11 at 20:24
  • @Strip Nice thoery, but the OP has a fine command of the English language: http://stackoverflow.com/questions/7325073/how-could-i-get-over-my-programming-problems. – Tim Lloyd Sep 06 '11 at 20:36
  • 1
    @chibacity: Ah, well. So much for giving people the benefit of the doubt. – StriplingWarrior Sep 06 '11 at 22:01
  • And I'd argue that it's completely possible to fully understand the behavior of polymorphism, without knowing the exact definitions of certain terms. – Alex Apr 26 '15 at 16:52

8 Answers8

51

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);
        }
    }
Russ Clarke
  • 17,511
  • 4
  • 41
  • 45
25

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.

Majid
  • 13,853
  • 15
  • 77
  • 113
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
  • 6
    Simple Words sometimes means more than a lecture, thanks for sharing your mind's clarity. – Obzajd Sep 23 '11 at 23:29
  • your second paragraph is incorrect, I believe. You need to switch Car and SuperCar around - every time you need the parent (SuperCar) you can pass in a child (Car) – Jonesopolis Jan 26 '15 at 16:56
  • @Jonesy I'm quite sure he's using common world semantics here, _SuperCar_ being a better, enhanced car. An that would then be a _SubCar_ if using programmer semantics. – Alex Apr 26 '15 at 16:49
23

Let's use my favorite verb and we find:

http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29

http://msdn.microsoft.com/en-us/library/ms173152%28v=vs.80%29.aspx

Polymorphism and Inheritance are pivotal, need-to-be-ingrained and fundamental concepts to C# and object oriented programming. saying you know C# and not this is like knowing how to speak English and have no concept of what the alphabet is. Sorry to be blunt, but it is true.

From the Wiki link above (this is not mine), here is an example of Polymorphism (converted to C#...)

public class Animal
{
    public virtual String talk() { return "Hi"; }
    public string sing() { return "lalala"; }
}

public class Cat : Animal
{
    public override String talk() { return "Meow!"; }
}

public class Dog : Animal
{
    public override String  talk() { return "Woof!"; }
    public new string sing() { return "woofa woofa woooof"; }
}

public class CSharpExampleTestBecauseYouAskedForIt
{
    public CSharpExampleTestBecauseYouAskedForIt()
    {
        write(new Cat());
        write(new Dog());
    }

    public void write(Animal a) {
        System.Diagnostics.Debug.WriteLine(a.talk());
    }

}
VictorySaber
  • 3,084
  • 1
  • 27
  • 45
Ryan Ternier
  • 8,714
  • 4
  • 46
  • 69
11

Let's explain this in a more interesting way. Inheritance is the way derived class make use of the functionality of base class. Polymorphism is the way base class make use of implementation of the derived class.

public class Triangle :Shape {
 public int getSides() {
  return 3;
 }
}

}
public class Shape {
 public boolean isSharp(){
  return true;
 }
 public virtual int getSides(){
  return 0 ;
 }

 public static void main() {
  Triangle tri = new Triangle();
  System.Console.WriteLine("Triangle is a type of sharp? " + tri.isSharp());  //Inheritance 
  Shape shape = new Triangle();
  System.Console.WriteLine("My shape has " + shape.getSides() + " sides.");   //Polymorphism 
 }
}
Deyili
  • 151
  • 4
  • Now you said that, It's somehow got interesting topic to learn and use in my daily programming, not to avoid -as before. – Obzajd Sep 23 '11 at 23:31
8

Polymorphism is the act of overriding what you Inherited.

If you don't override it, it's not polymorphism, it's just inheritance.

Sean Bradley
  • 3,254
  • 1
  • 17
  • 10
6

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

PsCraft
  • 620
  • 1
  • 8
  • 18
6

When you derive a class from a base class, the derived class will inherit all members of the base class except constructors, though whether the derived class would be able to access those members would depend upon the accessibility of those members in the base class. C# gives us polymorphism through inheritance. Inheritance-based polymorphism allows us to define methods in a base class and override them with derived class implementations. Thus if you have a base class object that might be holding one of several derived class objects, polymorphism when properly used allows you to call a method that will work differently according to the type of derived class the object belongs to.

Reference: http://www.codeproject.com/Articles/1445/Introduction-to-inheritance-polymorphism-in-C

Richard Gray
  • 149
  • 2
  • 11
1

It's all about behaviours.

A class declares a certain behaviour (interface or contract):

That class may also define that behaviour (implementation) or delegate either the whole or part of it to any of its subclasses:

In pseudocode:

class Animal {
    method walk()
    method speak()
    method jump()
    // ... here goes the implementation of the methods
}

Through subclassing you make a class inherit another class' behaviour.

When the implementation of a method is delegated to subclasses, the method is called abstract in the base class and, in languages like Java, the whole base class becomes abstract as well:

abstract class Animal {
    method walk() {
       doWalk()
    }
    method speak() {
       print "hi, I am an animal!"
    }
    abstract method jump() // delegated to specific animals
}

class Horse inherits from Animal {
    override method walk() {
        doWalkLikeAHorse()
    }
    override method speak() {
        print "hi, I am a horse!"
    }
    override method jump() { 
        doJumpLikeAHorse()
    }
}

class Elephant inherits from Animal {
    override method walk() {
        doWalkLikeAnElephant()
    }
    override method speak() {
        print "hi, I am an elephant!"
    }
    override method jump() { 
        throw error "Sorry, I can't jump!!"
    } 
}

A class' behaviour is by default virtual, which means that any class methods may be overridden by any subclasses. This is how it works in languages like C# and Java, but not necessarily in C++, for example.

In substance, the behaviour of a base class is only virtual and may assume "multiple" (poly) "different forms" (morphs) when subclasses override that virtual behaviour. That's why it's called polymorphism. In pseudocode:

function makeAnimalSpeak(Animal animal) {
    animal.speak();
}

makeAnimalSpeak(new Elephant()) // output: "hi, I am an elephant"
makeAnimalSpeak(new Horse())  // output: "hi, I am a horse"

Other people have offered you better examples here.

In languages like C# and Java you have the idea of interface (which does not exist in C++), which is just a declaration of a behaviour. An interface, unlike a class, has no obligation to implement a behaviour. It's just a declaration. Any class may implement that behaviour, no matter what base class they inherit from. In pseudocode:

interface FlyingBeing {
    method fly()
}

class FlyingPig inherits from Animal implements FlyingBeing {
    method fly() {
       print "hey, look at me, I am a flying pig!!"
    }
}