Polymorphism vs Overloading methods

Hi guys,
Been reading some more books and i was wondering if anyone could clarify the difference between polymorphism and method overloading. As i understood it method overloading is a type of polymorphism yet im sure there must be more to it.

More importantly could someone clarify when you would use one rather than the other?

Rgds

Fraz


Comments

  • Overloading is a way to use polymorphism - so it's not a situation where you could use one over the other.

    So Overloading would be one instance of polymorphism - but polymorphism is actually a more abstract concept.

    So for example - if you have a base or abstract class or an interface, you are using polymorphism.

    A classic text-book example of this is having an abstract class called "Animal"

    On it Animal has a method called "MakeASound". Now, since Animal is abstract - there is no code inside of the MakeASound method because Animal expects a more specific type to define how MakeASound works.

    So lets say you make a "Dog" class that inherits the "Animal" class. Because Dog inherits Animal - Dog is required to define functionality for the MakeASound method. Inside that method for Dog, you would put "Console.WriteLine("Bark");"

    Now let's say you have a "Cat" class. Inside the MakeASound method for the cat class you would put "Console.WriteLine("Meow");"

    Now let's say you have a method somewhere called "PokeAnimal" and it looks something like this...

    [code]
    public void PokeAnimal(Animal animal)
    {
    Animal.MakeASound();
    }
    [/code]

    This method doesn't care what kind of animal it is passed - it could be a dog or a cat, either way - when the animal is poked it will make a sound, that's all the method knows. Sooo - if you pass it a dog, it will do one thing, but if you pass it a cat, it will do another thing. All the while - it's the same method.

    Now, Overloading means you actually have more than one actual method with the same name - but it is actually different code.

    So if you have a method like so:

    public void MakeCreatureHappy(Dog creature)
    {
    creature.Pet();
    }

    public void MakeCreatureHappy(Cat creature)
    {
    creature.Pet();
    }

    public void MakeCreatureHappy(Snake creature)
    {
    creature.FeedMouse();
    }

    public void MakeCreatureHappy(Insect creature)
    {
    creature.TurnOnHeatLamp();
    }


    then depending on what kind of animal you pass to this method, the appropriate version of the method will be called.

    So if you give the method a cat - the cat will be pet, if you give the method a snake, the snake will be fed - etc.

    As far as the code that is using the method is concerned, you passed it a value and it doesn't care what kind of value (as long as that value is a handled type).
  • Hi DataDink, thanks for the reply. Regardin the code I'm a little confused with the methods argument (Animal animal) but I'm pretty sure I have covered this so I'm gonna have a look into that myself. Apart from that, ur reply was exactly what I was looking for, thanks again

    Rgds

    Fraz
  • Animal animal

    the Animal with the capitol letter would be a Type that is named Animal, and "animal" is just the name of the variable passed to the method.
  • I don't understand Animal being a type.I understand type in the sense of int,char,double etc.is this type refering to the superclass because it's argument is an object which inherits from the abstract Animal class. Therefore this method won't accept a class not associated with the Animal class or am I just speaking ****?

    The method body,should this then b animal.makeasound rather than Animal.makeasound?

    Cheers again

    Fraz

    EDIT: do u know where i can get some info on passing objects into methods, i have been looking for some info on it and only found one post on another forum (wont say name as im assuming ill get into trouble for doing so) .
  • ah - ok - I think I know where the confusion is.

    So just because you can't instantiate an actual superclass - it doesn't mean you can't pass an instantiated subclass to a method AS a superclass...


    So even though I say:
    var myCreature = new Cat();


    "myCreature" can be passed to any method that requires either a Cat - or an Animal - or heck - any method that requires an "object" will work also.

    This is the essence of polymorphism.

    Now, in the method that receives an animal - there will be no knowledge of a method like let's say "PounceTarget" - because that is a cat only method. The method that receives an Animal only knows about the Animal methods and properties.

    But if you pass a Cat into a method asking for an animal, the cat code will still be executed - just blindly by the receiving method.

    does that help?
  • you can pass an instantiated subclass to a methods [ which is say defined in body of the main() method] AS a superclass.

    ok thats completely over my head :( n why would u want to pass it as a superclass and not a subclass?

    so the general gist of things is as follows?

    (1) You create a superclass (class A) with abstract methods.

    (2) You create a couple other classes (B,C and D) each inheriting class A and each declaring the abstract methods n then instantiate them. ( im assuming its the same if the superclass has virtual methods and they are then inherited by the subclasses and overriden?)

    (3) A new method is delcared inside your main() method. you can pass the objects of the subclasses B,C and D into this method using their type which is A (you said Animal in your above example so im guessing its A here) and then the corresponding object name (B, C or D).

    (4) The method body will then be able to call a method (the same one which was declared abstract in A and defined in B,C or D) using A as class ( i.e. A.Methodname(); ). the program will know which object and therefore which concrete method to use from the object passed into it as its argument?

    If the above is wrong could you please highlight where

    if on the other hand the above is correct (happy days) then your basically just using a method to access other methods. I have a feeling im missing something, but the only real reason for using this is if your passing in your objects in such a way that you dont actually know which one is being passed in i.e. a random generator is selecting which object is being passed in otherwise you could just call the object and the corresponding method in your Main() method?

    Thanks again DataDink

    Rgds

    Fraz
  • yes that sounds correct.

    So if you're wondering "why in the world would you ever pass something as superclass A and not concrete classes B, C, or D?"

    This is actually the whole reason why you wrote an A superclass in the first place.

    Let me give you a kind of real-life example...

    Let's say your writing a video game. Your main character can hit any animal in the game with his sword - and the result is that animal will make whatever sound is appropriate for that animal.

    Let's see what the code and maintenance would look like if you didn't create an animal super-class


    [code]
    public void SwingWeapon(Point swingLocation, Cat[] cats, Dog[] dogs, Snake[] snakes, Grasshopper[] gHoppers)
    {
    foreach (var cat in cats)
    if (cat.Location == swingLocation)
    cat.Meow();
    foreach (var dog in dogs)
    if (dog.Location == swingLocation)
    dog.Bark();
    foreach (var snake in snakes)
    if (snake.Location == swingLocation)
    snake.Hiss();
    foreach (var gHopper in gHoppers)
    if (gHopper.Location == swingLocation)
    gHopper.Chirp();
    }
    [/code]

    But wait - uh oh, you added a new type of animal to your game in the latest expansion and now when your hero swings his sword at the Crows they don't caw! Well bummer - so I have, let's say about 2 billion lines of code to search through and find every place that I am doing something that affects all animals - Starting with SwingWeapon.

    I'm also going to have to pass all of the crows in my game to that method so I'm going to have to change its "signature". This means that any thing else that was calling the method SwingWeapon is also going to have to know to pass in all of the crows...
    [code]
    public void SwingWeapon(Point swingLocation, Cat[] cats, Dog[] dogs, Snake[] snakes, Grasshopper[] gHoppers, Crows[] crows)
    [/code]

    But wait - Now let's look at this method using a superclass "Animal"

    [code]
    public void SwingWeapon(Point swingLocation, Animal[] animals)
    {
    foreach (var animal in animals)
    if (swingLocation == animal.Location)
    animal.MakeNoise();
    }
    [/code]
    Wow - that took care of all of my dogs, cats, spiders, leeches, crickets, traffic gnomes, and tigers!

    Ok - now same problem - I made an expansion for my game and added a new animal - Crows...

    But wait... I don't have to change anything because when I added my crows to the game I just added them to the Animal array. They fit in that array because they were subclassed from the Animal superclass.

    Yay - no extra work for me!
  • Shoot - ya, you're right - I just caught that typo - my original method body should have been animal.MakeASound()

    Sorry if that's what confused you.
  • Hi DataDink, yeah that was one of the points i was stubling on. Thanks very much for clarifying polymorphism. The examples were spot on but the comparison to what you would have to do if you didnt incorporate it was what made it really shine. Thanks again, ur made my weekend :)

    i do have one final question, im not familar with the below piece of code.

    "(var animal in animals)"

    what does this actually mean?

    Hope uve had a nice wknd

    Rgds

    Fraz
  • So in there I am using what is called a foreach loop.

    A foreach loop itterates through any kind of collection or array.
    The statement there is basically saying
    Run a loop once for each item in the given collection. Each time you loop give the value of the current itteration to "SomeVariable".

    So what I'm saying is

    For Each item in Animals do a loop and make the variable named "animal" have the value of the current item from Animals.

    So in a loop like:
    [code]
    foreach (var animal in Animals)
    {
    // Now each time this block is run - "animal" will hold the next item from the Animals array.
    }
    [/code]

    If your also confused as to what "var" is - I believe this was added in C# 3.0

    Instead of saying:
    string MyString = "This is obviously a string";

    You can say:
    var MyString = "So there is no need to really say that this is a string";

    var will allow a variable to be declared by the value you are assigning it.

    One thing this does is it lines up your code a little better. It also allows you to work without having to fully resolve types or even know the exact type that you are working with - because in alot of cases you don't really care - you are just passing data from one thing to another.
  • aye ok cool. i think most of the books n articles i have read have focused on c# 2.0 so thats probably why i hadnt see it before.

    Cheers for clarify that.

    Rgds

    Fraz
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion