By UnkwnTech


2009-06-23 08:14:21 8 Comments

What is polymorphism, what is it for, and how is it used?

28 comments

@Olivier Rogier 2019-10-02 08:19:22

What is polymorphism?

Polymorphism is the ability to:

  • Invoke an operation on an instance of a specialized type by only knowing its generalized type while calling the method of the specialized type and not that of the generalized type: it is dynamic polymorphism.

  • Define several methods having the save name but having differents parameters: it is static polymorphism.

The first if the historical definition and the most important.

What is polymorphism used for?

It allows to create strongly-typed consistency of the class hierarchy and to do some magical things like managing lists of objects of differents types without knowing their types but only one of their parent type, as well as data bindings.

Strong and weak typing

Sample

Here are some Shapes like Point, Line, Rectangle and Circle having the operation Draw() taking either nothing or either a parameter to set a timeout to erase it.

public class Shape
{
 public virtual void Draw()
 {
   DoNothing();
 }
 public virtual void Draw(int timeout)
 {
   DoNothing();
 }
}

public class Point : Shape
{
 int X, Y;
 public override void Draw()
 {
   DrawThePoint();
 }
}

public class Line : Point
{
 int Xend, Yend;
 public override Draw()
 {
   DrawTheLine();
 }
}

public class Rectangle : Line
{
 public override Draw()
 {
   DrawTheRectangle();
 }
}

var shapes = new List<Shape> { new Point(0,0), new Line(0,0,10,10), new rectangle(50,50,100,100) };

foreach ( var shape in shapes )
  shape.Draw();

Here the Shape class and the Shape.Draw() methods should be marked as abstract.

They are not for to make understand.

Explaination

Without polymorphism, using abstract-virtual-override, while parsing the shapes, it is only the Spahe.Draw() method that is called as the CLR don't know what method to call. So it call the method of the type we act on, and here the type is Shape because of the list declaration. So the code do nothing at all.

With polymorphism, the CLR is able to infer the real type of the object we act on using what is called a virtual table. So it call the good method, and here calling Shape.Draw() if Shape is Point calls the Point.Draw(). So the code draws the shapes.

More readings

C# - Polymorphism (Level 1)

Polymorphism in Java (Level 2)

Polymorphism (C# Programming Guide)

Virtual method table

@paxdiablo 2009-06-23 08:44:54

If you think about the Greek roots of the term, it should become obvious.

  • Poly = many: polygon = many-sided, polystyrene = many styrenes (a), polyglot = many languages, and so on.
  • Morph = change or form: morphology = study of biological form, Morpheus = the Greek god of dreams able to take any form.

So polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types).

For example, in many languages, integers and floats are implicitly polymorphic since you can add, subtract, multiply and so on, irrespective of the fact that the types are different. They're rarely considered as objects in the usual term.

But, in that same way, a class like BigDecimal or Rational or Imaginary can also provide those operations, even though they operate on different data types.

The classic example is the Shape class and all the classes that can inherit from it (square, circle, dodecahedron, irregular polygon, splat and so on).

With polymorphism, each of these classes will have different underlying data. A point shape needs only two co-ordinates (assuming it's in a two-dimensional space of course). A circle needs a center and radius. A square or rectangle needs two co-ordinates for the top left and bottom right corners and (possibly) a rotation. An irregular polygon needs a series of lines.

By making the class responsible for its code as well as its data, you can achieve polymorphism. In this example, every class would have its own Draw() function and the client code could simply do:

shape.Draw()

to get the correct behavior for any shape.

This is in contrast to the old way of doing things in which the code was separate from the data, and you would have had functions such as drawSquare() and drawCircle().

Object orientation, polymorphism and inheritance are all closely-related concepts and they're vital to know. There have been many "silver bullets" during my long career which basically just fizzled out but the OO paradigm has turned out to be a good one. Learn it, understand it, love it - you'll be glad you did :-)


(a) I originally wrote that as a joke but it turned out to be correct and, therefore, not that funny. The monomer styrene happens to be made from carbon and hydrogen, C8H8, and polystyrene is made from groups of that, (C8H8)n.

Perhaps I should have stated that a polyp was many occurrences of the letter p although, now that I've had to explain the joke, even that doesn't seem funny either.

Sometimes, you should just quit while you're behind :-)

@AakashM 2009-06-23 09:26:00

Greek, not Latin :) (the 'y' and 'ph' are the giveaways). And in the Greek, 'morph-' is just 'shape', or 'form' - the English meaning of 'change shape' for 'morph' is a later development

@alternative 2011-04-16 20:27:11

Polymorphism is not related to OOP, but OOP is related to polymorphism because it inherently supports it (assuming its a decent OOP language). Look at FP for other examples of polymorphism.

@ony 2013-05-17 09:51:04

I'd like to rise simple question about polymorphism. Is function that takes base type as its argument (ex void foo(Base &x) in C++) can be considered polymorphic? Note that we shouldn't consider the fact that final code will have only one body of that function since optimizer can make different bodies optimized differently and can have different behavior. Of course compiler should be able to prove that type of objects received by that function can be determined in compile time which is easy to do if your code is foo(DerivedA()); foo(DerivedB());.

@Jo Smo 2014-05-13 09:48:21

These 2 lines did the trick for me: Poly = many and Morph = change or form

@Dirk 2016-10-12 14:21:18

Polyp is short for polypo(u)s. And pous is foot in greek. ;-)

@Shaun Luttin 2017-01-29 02:01:48

This answer describes subtyping which is but one form of polymorphism. en.wikipedia.org/wiki/Subtyping

@paxdiablo 2017-01-29 02:39:24

Shaun, the paragraph immediately after the bullet points is the definitive (literally) one and makes no such limitation to said definition. Everything after that is just examples of polymorphism.

@JRafaelM 2017-04-18 00:54:22

Yeah @ShaunLuttin, actually it recently came to my knowledge another nice type of polimorphism called polimorphism by composition, you guys take a look on that: en.wikipedia.org/wiki/Composition_over_inheritance

@Shaun Luttin 2017-04-18 01:32:54

@paxdiablo The paragraph immediately after the bullet points does not match my understanding. Polymorphism lets us run the same routine/operation on different types at different times. One way to do that is to present the same interface for different underlying types. Another way to do that is method overloading (ad hoc polymorphism) which does not require presenting the same interface for different underlying types. The definitive paragraph from your answer leaves out that way of doing it.

@paxdiablo 2017-04-18 03:21:28

@Shaun, I think you may be using the term "interface" in a far too-literal/constrictive sense - I meant it as an English term rather than a definition specific to some arbitrary computer language. It doesn't mean exactly the same function with exactly the same parameters, it's simply a way of affecting "objects" in the same way irrespective of their underlying concrete type. This can include method overloading with different parameter types as well as the more pure form of polymorphism.

@Łukasz Wiatrak 2017-09-09 08:22:16

"(...) integers and floats are implicitly polymorphic since you can add, subtract, multiply (...), irrespective of the fact that the types are different" - is this statement true in general, for every programming language? It is true for languages like C++ (when using templates) or JavaScript, but what about e.g. C#? I don't think we are able to have a method in C# that uses number operators without knowing on which exact type it operates on.

@g.pickardou 2019-03-19 08:05:28

Explicitly wrong about linking inheritance with polymorphism. Anyone who tries the understand deeply concept will misguided with this way. Also the very starting thought regarding numbers although may be true, is not useful, especially as a first thought. Does not mention the "is a" relation...

@paxdiablo 2019-03-20 06:51:13

@g.pickardou, the sentence linking those two begins "The classic example ...", it's not meant to be a restrictive requirement that all polymorpism is related to inheritance. I'm well aware that polymorphism can have other means of expression (such as interfaces) but I'm also aware that, should I attempt an exhaustive answer, it would be so voluminous as to be useless :-) If you have some specific suggestions on how to improve the answer, I'm happy to entertain them.

@Aaron 2019-06-13 15:51:12

Regarding your edit : “Explaining a joke is like dissecting a frog. You understand it better but the frog dies in the process.” - E.B. White

@Hassan Tareq 2015-04-17 19:15:45

Polymorphism:

Different execution according to the instance of the class, not the type of reference variable.

An interface type reference variable can refer to any of the class instances that implement that interface.

@BKSpurgeon 2016-10-29 00:17:35

Simple Explanation by analogy

The President of the United States employs polymorphism. How? Well, he has many advisers:

  1. Military Advisers
  2. Legal Advisers
  3. Nuclear physicists (as advisers)
  4. Medical advisers
  5. etc etc.

Everyone Should only be responsible for one thing: Example:

The president is not an expert in zinc coating, or quantum physics. He doesn't know many things - but he does know only one thing: how to run the country.

It's kinda the same with code: concerns and responsibilities should be separated to the relevant classes/people. Otherwise you'd have the president knowing literally everything in the world - the entire Wikipedia. Imagine having the entire wikipedia in a class of your code: it would be a nightmare to maintain.

Why is that a bad idea for a president to know all these specific things?

If the president were to specifically tell people what to do, that would mean that the president needs to know exactly what to do. If the president needs to know specific things himself, that means that when you need to make a change, then you'll need to make it in two places, not just one.

For example, if the EPA changes pollution laws then when that happens: you'd have to make a change to the EPA Class and also the President class. Changing code in two places rather than one can be dangerous - because it's much harder to maintain.

Is there a better approach?

There is a better approach: the president does not need to know the specifics of anything - he can demand the best advice, from people specifically tasked with doing those things.

He can use a polymorphic approach to running the country.

Example - of using a polymorphic approach:

All the president does is ask people to advise him - and that's what he actually does in real life - and that's what a good president should do. his advisors all respond differently, but they all know what the president means by: Advise(). He's got hundreds of people streaming into his office. It doesn't actually matter who they are. All the president knows is that when he asks them to "Advise" they know how to respond accordingly:

public class MisterPresident
{
    public void RunTheCountry()
    {
        // assume the Petraeus and Condi classes etc are instantiated.
        petraeus.Advise(); // # Petraeus says send 100,000 troops to Fallujah
        condolezza.Advise(); // # she says negotiate trade deal with Iran
        healthOfficials.Advise(); // # they say we need to spend $50 billion on ObamaCare
    }
}

This approach allows the president to run the country literally without knowing anything about military stuff, or health care or international diplomacy: the details are left to the experts. The only thing the president needs to know is this: "Advise()".

What you DON"T want:

public class MisterPresident
{
    public void RunTheCountry()
    {
        // people walk into the Presidents office and he tells them what to do
        // depending on who they are.

        // Fallujah Advice - Mr Prez tells his military exactly what to do.
        petraeus.IncreaseTroopNumbers();
        petraeus.ImproveSecurity();
        petraeus.PayContractors();

        // Condi diplomacy advice - Prez tells Condi how to negotiate

        condi.StallNegotiations();
        condi.LowBallFigure();
        condi.FireDemocraticallyElectedIraqiLeaderBecauseIDontLikeHim();

        // Health care

        healthOfficial.IncreasePremiums();
        healthOfficial.AddPreexistingConditions();
    }
}

NO! NO! NO! In the above scenario, the president is doing all the work: he knows about increasing troop numbers and pre-existing conditions. This means that if middle eastern policies change, then the president would have to change his commands, as well as the Petraeus class as well. We should only have to change the Petraeus class, because the President shouldn't have to get bogged down in that sort of detail. He doesn't need to know about the details. All he needs to know is that if he makes one order, everything will be taken care of. All the details should be left to the experts.

This allows the president to do what he does best: set general policy, look good and play golf :P.

How is it actually implemented - through a base class or a common interface

That in effect is polymorphism, in a nutshell. How exactly is it done? Through "implementing a common interface" or by using a base class (inheritance) - see the above answers which detail this more clearly. (In order to more clearly understand this concept you need to know what an interface is, and you will need to understand what inheritance is. Without that, you might struggle.)

In other words, Petraeus, Condi and HealthOfficials would all be classes which "implement an interface" - let's call it the IAdvisor interface which just contains one method: Advise(). But now we are getting into the specifics.

This would be ideal

    public class MisterPresident
    {
            // You can pass in any advisor: Condi, HealthOfficials,
            //  Petraeus etc. The president has no idea who it will 
            // be. But he does know that he can ask them to "advise" 
            // and that's all Mr Prez cares for.

        public void RunTheCountry(IAdvisor governmentOfficer)
        {             
            governmentOfficer.Advise();              
        }
    }


    public class USA
    {
        MisterPresident president;

        public USA(MisterPresident president)
        {
            this.president = president;
        }

        public void ImplementPolicy()
        {
            IAdvisor governmentOfficer = getAdvisor(); // Returns an advisor: could be condi, or petraus etc.
            president.RunTheCountry(governmentOfficer);
        }
    }

Summary

All that you really need to know is this:

  • The president doesn't need to know the specifics - those are left to others.
  • All the president needs to know is to ask who ever walks in the door to advice him - and we know that they will absolutely know what to do when asked to advise (because they are all in actuality, advisors (or IAdvisors :) )

I really hope it helps you. If you don't understand anything post a comment and i'll try again.

@Iman Sedighi 2017-01-09 09:06:05

Fantastic example! Thanks.

@thanhtang 2017-08-16 02:33:46

Very interesting analogy. Thank you.

@T.T.T. 2018-01-25 23:41:08

@bkspurgeon: why cant we jsut wrap the 3 separate calls in one function to abstract it? why polymorphism here? heck just wrap all advisors in 1 function?

@BKSpurgeon 2018-01-25 23:53:56

@T.T.T. because (1) everytime you have a new advisor then you'd have to change the president class - you don't want to make x2 changes. just one. (2) secondly, if you have to change an existing advisor, then you might have to go back and change one of those three calls in the president class - you only really want to make one change, not two. (3) if you had three separate calls then you would have to ask, within the president class: if healthAdvisor? then do this: and if petraus then do that etc. this pattern will need to be repeated and that is unecessary and complicated. see above edit.

@T.T.T. 2018-01-26 00:09:06

@bkspurgeon: Hi, for point (1), I only see that in your last "ideal" code example, where you pass in the advisor, otherwise in the first example, it seems there would be a change to the president class if you got a new advisor...right? for point (2), sure three calls instead of one, but I guess I still just see that is abstraction via 1 function call. Your last example in contrast with the what not to do example helps the most, (even thought you added a new type of "IAdvisor ", may be helpful to describe that). ...thanks for helping me understand.

@BKSpurgeon 2018-01-26 00:10:55

@T.T.T. yes you are right. but i have to slowly introduce the concept to the readers otherwise they will not understand. i have added further changes. please advise if clarifications are needed

@T.T.T. 2018-01-26 00:19:00

@bkspurgeon: awesome, yes now i see it coming together. Haven't seen the terms base class and interface used exchangeable before, but if that is OK in OOP, it makes sense. thank you for you slowly introducing the concepts, yes that does help.

@BKSpurgeon 2018-01-26 00:42:01

@T.T.T. base class vs interface is a design decision programmers have to make when doing polymorpism. see here for more details: stackoverflow.com/questions/56867/interface-vs-base-class

@Shaun Luttin 2017-01-29 01:28:18

Polymorphism allows the same routine (function, method) to act on different types.

Since many existing answers are conflating subtyping with polymorphism, here are three ways (including subtyping) to implement polymorphism.

  • Parameteric (generic) polymorphism allows a routine to accept one or more type parameters, in addition to normal parameters, and runs itself on those types.
  • Subtype polymorphism allows a routine to act on any subtype of its parameters.
  • Ad hoc polymorphism generally uses routine overloading to grant polymorphic behavior, but can refer to other polymorphism implementations too.

See also:

http://wiki.c2.com/?CategoryPolymorphism

https://en.wikipedia.org/wiki/Polymorphism_(computer_science)

@Antony Gibbs 2010-06-24 13:25:01

Polymorphism is when you can treat an object as a generic version of something, but when you access it, the code determines which exact type it is and calls the associated code.

Here is an example in C#. Create four classes within a console application:

public abstract class Vehicle
{
    public abstract int Wheels;
}

public class Bicycle : Vehicle
{
    public override int Wheels()
    {
        return 2;
    }
}

public class Car : Vehicle
{
    public override int Wheels()
    {
        return 4;
    }
}

public class Truck : Vehicle
{
    public override int Wheels()
    {
        return 18;
    }
}

Now create the following in the Main() of the module for the console application:

public void Main()
{
    List<Vehicle> vehicles = new List<Vehicle>();

    vehicles.Add(new Bicycle());
    vehicles.Add(new Car());
    vehicles.Add(new Truck());

    foreach (Vehicle v in vehicles)
    {
        Console.WriteLine(
            string.Format("A {0} has {1} wheels.",
                v.GetType().Name, v.Wheels));
    }
}

In this example, we create a list of the base class Vehicle, which does not know about how many wheels each of its sub-classes has, but does know that each sub-class is responsible for knowing how many wheels it has.

We then add a Bicycle, Car and Truck to the list.

Next, we can loop through each Vehicle in the list, and treat them all identically, however when we access each Vehicles 'Wheels' property, the Vehicle class delegates the execution of that code to the relevant sub-class.

This code is said to be polymorphic, as the exact code which is executed is determined by the sub-class being referenced at runtime.

I hope that this helps you.

@wired00 2014-10-30 02:09:22

I think this is a very good example for showing clearly the parent interface, and that it is not until the object is instantiated that a concrete version is required, ie vehicle vs car

@Oliver Williams 2017-01-06 19:50:34

I would say this is the clearest example, though if you are a PHP programmer this link might be easier to review FIRST, and then still look at this one after: code.tutsplus.com/tutorials/…

@Oliver Williams 2017-01-06 19:54:28

Also (beyond the scope of the OP) to note that we're constraining analysis to known objects; we are not passing an object (like an import file) and then determining what type it is (Excel, CSV, YAML, SQL, etc. etc.). To do this one would need some sort of factory class for Class_Excel, Class_CSV to be called, or have a Reader class called. Either way, some sort of iterative if/then/else is going to have to be stored somewhere.

@T.T.T. 2018-01-25 23:21:21

@Antony Gibbs: this is a really good example (a list of the generic types) that makes sense to me....otherwise what is the big deal of having each class have it's own wheels function without inheriting from a base class? Are there any more concepts besides list that would be good for polymorphic?

@Raghav Navada 2017-04-12 06:21:45

Polymorphism gives you the ability to create one module calling another, and yet have the compile time dependency point against the flow of control instead of with the flow of control.

By using polymorphism, a high level module does not depend on low-level module. Both depend on abstractions. This helps us to apply the dependency inversion principle(https://en.wikipedia.org/wiki/Dependency_inversion_principle).

This is where I found the above definition. Around 50 minutes into the video the instructor explains the above. https://www.youtube.com/watch?v=TMuno5RZNeE

@Ajay Patel 2011-11-04 05:17:46

From Understanding and Applying Polymorphism in PHP, Thanks Steve Guidetti.

Polymorphism is a long word for a very simple concept.

Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.

The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way. A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends on what it is connected to and the context in which it is used — but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task.

In the programming world, polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.

@thewpfguy 2013-03-29 03:53:54

isn't the button analogy related more to the concept of abstraction?

@Someone 2015-03-16 14:14:29

@BoltClock 2015-03-16 15:10:17

@Mantriur: This is indeed plagiarized, and we have rules against that: stackoverflow.com/help/referencing But given its score now and the fact that old posts are exempt from rep loss on answer deletion, I'm not sure if deleting it now outright would improve anything. The next best alternative would be to just edit in the attribution on behalf of the user, even though I strongly believe users are responsible for citing sources in their own answers.

@StubbornShowaGuy 2016-10-18 06:54:00

I believe it is incorrect to imply that polymorphism is specific to classes and/or object-oriented programming, seeing how ad hoc polymorphism or parametric polymorphism do not necessarily require classes and/or objects. I think what this answer is talking about is subtyping(also known as subtype polymorphism or inclusion polymorphism).

@Vahid 2016-10-02 21:51:05

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. In this example that is written in Java, we have three type of vehicle. We create three different object and try to run their wheels method:

public class PolymorphismExample {

    public static abstract class Vehicle
    {
        public int wheels(){
            return 0;
        }
    }

    public static class Bike extends Vehicle
    {
        @Override
        public int wheels()
        {
            return 2;
        }
    }

    public static class Car extends Vehicle
    {
        @Override
        public int wheels()
        {
            return 4;
        }
    }

    public static class Truck extends Vehicle
    {
        @Override
        public int wheels()
        {
            return 18;
        }
    }

    public static void main(String[] args)
    {
        Vehicle bike = new Bike();
        Vehicle car = new Car();
        Vehicle truck = new Truck();

        System.out.println("Bike has "+bike.wheels()+" wheels");
        System.out.println("Car has "+car.wheels()+" wheels");
        System.out.println("Truck has "+truck.wheels()+" wheels");
    }

}

The result is:

The Result

For more information please visit https://github.com/m-vahidalizadeh/java_advanced/blob/master/src/files/PolymorphismExample.java. I hope it helps.

@Cornelius 2016-12-13 11:00:20

Yes, but you didn't explain what are the benefits of polymorphism. There is obviously a shorter code, where you would delete the Vehicle class, and it would still work ( with a different object declaration, of course).

@Vahid 2016-12-14 03:49:48

I didn't explain, since the person who asked the question didn't ask about the benefits. He asked: "What is polymorphism, what is it for, and how is it used?". About the code, if you can do it better, please post your answer. So, our community can use it. Thanks for your comment.

@Cornelius 2016-12-14 08:51:13

Sorry, didn't want to sound rude, others didn't explain too. At least you bothered to type in the code. Anyways, he asked what is it for, but none of the examples on this page explain what is it for. You all just present a complex way to get the same results as this: s28.postimg.org/jq8vl6031/Poly.jpg and none cared to explain why would one want to do use polymorphism, what's its gain or purpose, what could have not been done if it wasn't used? All I see on this page is a proposition to climb up to your apartment using stairs, and not an elevator..

@Cornelius 2016-12-14 08:52:12

.. without noticing that one carries a flag pole that is too big to fit an elevator. I don't know how to post code, so I can't be of much help...

@Frank Zhang 2015-11-06 10:57:21

Polymorphism in OOP means a class could have different types, inheritance is one way of implementing polymorphism.

for example, Shape is an interface, it has Square, Circle, Diamond subtypes. now you have a Square object, you can upcasting Square to Shape automatically, because Square is a Shape. But when you try to downcasting Shape to Square, you must do explicit type casting, because you can't say Shape is Square, it could be Circle as well. so you need manually cast it with code like Square s = (Square)shape, what if the shape is Circle, you will get java.lang.ClassCastException, because Circle is not Square.

@Shourob Datta 2015-05-06 07:32:12

Polymorphism literally means, multiple shapes. (or many form) : Object from different classes and same name method , but workflows are different. A simple example would be:

Consider a person X.

He is only one person but he acts as many. You may ask how:

He is a son to his mother. A friend to his friends. A brother to his sister.

@Sanchit 2014-11-15 11:48:56

If anybody says CUT to these people

  1. The Surgeon
  2. The Hair Stylist
  3. The Actor

What will happen?

  • The Surgeon would begin to make an incision.
  • The Hair Stylist would begin to cut someone's hair.
  • The Actor would abruptly stop acting out of the current scene, awaiting directorial guidance.

So above representation shows What is polymorphism (same name, different behavior) in OOP.

If you are going for an interview and interviewer asks you tell/show a live example for polymorphism in the same room we are sitting at, say-

Answer - Door / Windows

Wondering How?

Through Door / Window - a person can come, air can come, light can come, rain can come, etc.

To understand it better and in a simple manner I used above example.. If you need reference for code follow above answers.

@Matt Klein 2017-01-27 05:49:03

I don't think this is a great example because it may lead inexperienced people to think that if two classes have a .foo() method, then they should share a common interface. However, this isn't true and leads to incorrect abstractions. An interface should define a role that is to be played, which may have many different implementations, but all pull from the same set of input and return something from the same set of output. The input into a x.cut(...) for a surgeon, stylist, or actor aren't the same, and neither is the output.

@Rohit 2014-04-08 13:01:44

Polymorphism is an ability of object which can be taken in many forms. For example in human class a man can act in many forms when we talk about relationships. EX: A man is a father to his son and he is husband to his wife and he is teacher to his students.

@Kcats Wolfrevo 2014-01-14 10:59:24

(I was browsing another article on something entirely different.. and polymorphism popped up... Now I thought that I knew what Polymorphism was.... but apparently not in this beautiful way explained.. Wanted to write it down somewhere.. better still will share it... )

http://www.eioba.com/a/1htn/how-i-explained-rest-to-my-wife

read on from this part:

..... polymorphism. That's a geeky way of saying that different nouns can have the same verb applied to them.

@Midimistro 2013-11-21 17:51:13

Polymorphism is the ability to use an object in a given class, where all components that make up the object are inherited by subclasses of the given class. This means that once this object is declared by a class, all subclasses below it (and thier subclasses, and so on until you reach the farthest/lowest subclass) inherit the object and it's components (makeup).

Do remember that each class must be saved in separate files.

The following code exemplifies Polymorphism:

The SuperClass:

public class Parent {
    //Define things that all classes share
    String maidenName;
    String familyTree;

    //Give the top class a default method
    public void speak(){
         System.out.println("We are all Parents");
    }
}

The father, a subclass:

public class Father extends Parent{
    //Can use maidenName and familyTree here
    String name="Joe";
    String called="dad";

    //Give the top class a default method
    public void speak(){
        System.out.println("I am "+name+", the father.");
    }
}

The child, another subclass:

public class Child extends Father {
    //Can use maidenName, familyTree, called and name here

    //Give the top class a default method
    public void speak(){
        System.out.println("Hi "+called+". What are we going to do today?");
    }
}

The execution method, references Parent class to start:

public class Parenting{
    public static void main(String[] args) {
        Parent parents = new Parent();
        Parent parent = new Father();
        Parent child = new Child();

        parents.speak();
        parent.speak();
        child.speak();
    }
}

Note that each class needs to be declared in separate *.java files. The code should compile. Also notice that you can continually use maidenName and familyTree farther down. That is the concept of polymorphism. The concept of inheritance is also explored here, where one class is can be used or is further defined by a subclass.

Hope this helps and makes it clear. I will post the results when I find a computer that I can use to verify the code. Thanks for the patience!

@Yehosef 2014-11-09 10:13:35

note that every child is not a parent so this structure is wrong. The top class should be Child (if you're not just starting with "Person") which will always be true except for Adam. You could set his parent_id to null since the Creator cannot be defined with any construct of human intellect.

@Tony Stark 2013-02-05 13:41:27

Polymorphism:

It is the concept of object oriented programming.The ability of different objects to respond, each in its own way, to identical messages is called polymorphism.

Polymorphism results from the fact that every class lives in its own namespace. The names assigned within a class definition don’t conflict with names assigned anywhere outside it. This is true both of the instance variables in an object’s data structure and of the object’s methods:

  • Just as the fields of a C structure are in a protected namespace, so are an object’s instance variables.

  • Method names are also protected. Unlike the names of C functions, method names aren’t global symbols. The name of a method in one class can’t conflict with method names in other classes; two very different classes can implement identically named methods.

Method names are part of an object’s interface. When a message is sent requesting that an object do something, the message names the method the object should perform. Because different objects can have methods with the same name, the meaning of a message must be understood relative to the particular object that receives the message. The same message sent to two different objects can invoke two distinct methods.

The main benefit of polymorphism is that it simplifies the programming interface. It permits conventions to be established that can be reused in class after class. Instead of inventing a new name for each new function you add to a program, the same names can be reused. The programming interface can be described as a set of abstract behaviors, quite apart from the classes that implement them.

Examples:

Example-1: Here is a simple example written in Python 2.x.

class Animal:
    def __init__(self, name):    # Constructor of the class
        self.name = name
    def talk(self):              # Abstract method, defined by convention only
        raise NotImplementedError("Subclass must implement abstract method")

class Cat(Animal):
    def talk(self):
        return 'Meow!'

class Dog(Animal):
    def talk(self):
        return 'Woof! Woof!'

animals = [Cat('Missy'),
           Dog('Lassie')]

for animal in animals:
    print animal.name + ': ' + animal.talk()

Example-2: Polymorphism is implemented in Java using method overloading and method overriding concepts.

Let us Consider Car example for discussing the polymorphism. Take any brand like Ford, Honda, Toyota, BMW, Benz etc., Everything is of type Car.

But each have their own advanced features and more advanced technology involved in their move behavior.

Now let us create a basic type Car

Car.java

public class Car {

    int price;
    String name;
    String color;

    public void move(){
    System.out.println("Basic Car move");
    }

}

Let us implement the Ford Car example.

Ford extends the type Car to inherit all its members(properties and methods).

Ford.java

public class Ford extends Car{
  public void move(){
    System.out.println("Moving with V engine");
  }
}

The above Ford class extends the Car class and also implements the move() method. Even though the move method is already available to Ford through the Inheritance, Ford still has implemented the method in its own way. This is called method overriding.

Honda.java

public class Honda extends Car{
  public void move(){
    System.out.println("Move with i-VTEC engine");
  }
}

Just like Ford, Honda also extends the Car type and implemented the move method in its own way.

Method overriding is an important feature to enable the Polymorphism. Using Method overriding, the Sub types can change the way the methods work that are available through the inheritance.

PolymorphismExample.java

public class PolymorphismExample {
  public static void main(String[] args) {
    Car car = new Car();
    Car f = new Ford();
    Car h = new Honda();

    car.move();
    f.move();
    h.move();

  }
}

Polymorphism Example Output:

In the PolymorphismExample class main method, i have created three objects- Car, Ford and Honda. All the three objects are referred by the Car type.

Please note an important point here that A super class type can refer to a Sub class type of object but the vice-verse is not possible. The reason is that all the members of the super class are available to the subclass using inheritance and during the compile time, the compiler tries to evaluate if the reference type we are using has the method he is trying to access.

So, for the references car,f and h in the PolymorphismExample, the move method exists from Car type. So, the compiler passes the compilation process without any issues.

But when it comes to the run time execution, the virtual machine invokes the methods on the objects which are sub types. So, the method move() is invoked from their respective implementations.

So, all the objects are of type Car, but during the run time, the execution depends on the Object on which the invocation happens. This is called polymorphism.

@srk 2017-01-08 10:41:23

Overloading concept has nothing to do with inheritance and Polymorphism.

@Shaun Luttin 2017-01-29 02:06:59

@srk Method overloading is one way of implementing polymorphism. It's often categorized as static or ad hoc polymorphism. wiki.c2.com/?CategoryPolymorphism

@sjith 2013-03-02 16:45:05

In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.

@Abe Miessler 2012-10-17 21:18:28

I know this is an older question with a lot of good answers but I'd like to include a one sentence answer:

Treating a derived type as if it were it's base type.

There are plenty of examples above that show this in action, but I feel this is a good concise answer.

@Shaun Luttin 2017-01-29 01:06:31

This is subtyping, which is only one kind of polymorphism.

@Abe Miessler 2017-01-29 01:08:30

@ShaunLuttin can you point me to any resources to learn more about the other types of polymorphism?

@Shaun Luttin 2017-01-29 01:17:47

The are "ad hoc polymorphism" and "parameteric polymorphism" in addtion to "subtype polymorphism".

@Shaun Luttin 2017-01-29 02:04:58

Here is a resource for you: wiki.c2.com/?CategoryPolymorphism

@Tony Delroy 2011-06-16 06:07:31

I've provided a high-level overview of polymorphism for another question:

Polymorphism in c++

Hope it helps. An extract...

...it helps to start from a simple test for it and definition of [polymorphism]. Consider the code:

Type1 x;
Type2 y;

f(x);
f(y);

Here, f() is to perform some operation and is being given the values x and y as inputs. To be polymorphic, f() must be able to operate with values of at least two distinct types (e.g. int and double), finding and executing type-appropriate code.

( continued at Polymorphism in c++ )

@Brian Scott 2010-06-24 13:09:59

Polymorphism in coding terms is when your object can exist as multiple types through inheritance etc. If you create a class named "Shape" which defines the number of sides your object has then you can then create a new class which inherits it such as "Square". When you subsequently make an instance of "Square" you can then cast it back and forward from "Shape" to "Square" as required.

@Vinko Vrsalovic 2010-06-24 13:07:26

Polymorphism is this:

class Cup {
   int capacity
}

class TeaCup : Cup {
   string flavour
}

class CoffeeCup : Cup {
   string brand
}

Cup c = new CoffeeCup();

public int measure(Cup c) {
    return c.capacity
}

you can pass just a Cup instead of a specific instance. This aids in generality because you don't have to provide a specific measure() instance per each cup type

@Shaun Luttin 2017-01-29 01:05:27

This is specifically subtype polymorphism.

@T.T.T. 2018-01-25 23:44:41

@vinko-vrsalovic: what is software development like in rural America?

@Alex Basson 2009-06-23 09:10:38

Polymorphism is the ability of the programmer to write methods of the same name that do different things for different types of objects, depending on the needs of those objects. For example, if you were developing a class called Fraction and a class called ComplexNumber, both of these might include a method called display(), but each of them would implement that method differently. In PHP, for example, you might implement it like this:

//  Class definitions

class Fraction
{
    public $numerator;
    public $denominator;

    public function __construct($n, $d)
    {
        //  In real life, you'd do some type checking, making sure $d != 0, etc.
        $this->numerator = $n;
        $this->denominator = $d;
    }

    public function display()
    {
        echo $this->numerator . '/' . $this->denominator;
    }
}

class ComplexNumber
{
    public $real;
    public $imaginary;

    public function __construct($a, $b)
    {
        $this->real = $a;
        $this->imaginary = $b;
    }

    public function display()
    {
        echo $this->real . '+' . $this->imaginary . 'i';
    }
}


//  Main program

$fraction = new Fraction(1, 2);
$complex = new ComplexNumber(1, 2);

echo 'This is a fraction: '
$fraction->display();
echo "\n";

echo 'This is a complex number: '
$complex->display();
echo "\n";

Outputs:

This is a fraction: 1/2
This is a complex number: 1 + 2i

Some of the other answers seem to imply that polymorphism is used only in conjunction with inheritance; for example, maybe Fraction and ComplexNumber both implement an abstract class called Number that has a method display(), which Fraction and ComplexNumber are then both obligated to implement. But you don't need inheritance to take advantage of polymorphism.

At least in dynamically-typed languages like PHP (I don't know about C++ or Java), polymorphism allows the developer to call a method without necessarily knowing the type of object ahead of time, and trusting that the correct implementation of the method will be called. For example, say the user chooses the type of Number created:

$userNumberChoice = $_GET['userNumberChoice'];

switch ($userNumberChoice) {
    case 'fraction':
        $userNumber = new Fraction(1, 2);
        break;
    case 'complex':
        $userNumber = new ComplexNumber(1, 2);
        break;
}

echo "The user's number is: ";
$userNumber->display();
echo "\n";

In this case, the appropriate display() method will be called, even though the developer can't know ahead of time whether the user will choose a fraction or a complex number.

@Pod 2009-06-23 09:22:42

That's not polymorphism. That's two classes having methods of the same name. They would need to be linked by a base class or interface called "displayable" or something similiar, and then other methods would simply care that the object is of type "displayable" rather than Complex or Fraction.

@Alex Basson 2009-06-23 09:37:29

I always thought polymorphism was "two classes having methods of the same nome." In fact, to quote Stephan Kochan (from whom I'm shameless ripping off this Fraction/Complex example), "the ability to share the same method name across different classes is known as polymorphism." (from Programming_In_Objective-C) He doesn't mention any need to link classes through a base class. Maybe it's different in different languages, I honestly don't know.

@vipirtti 2009-06-23 10:15:04

Even tough this defenition is quoted from a published book, I would still argue that it is incorrect. Especially since it seems to clash with every other, language agnostic defenition of polymorphism. And while the final result is the same as seen with polymorphism, I would argue that it is instead the dynamic typing that allows programmer be able to thrust that the correct implementation of a method among other, similary named methods is being called.

@Boris Pavlović 2009-06-23 08:21:05

Let's use an analogy. For a given musical script every musician which plays it gives her own touch in the interpretation.

Musician can be abstracted with interfaces, genre to which musician belongs can be an abstrac class which defines some global rules of interpretation and every musician who plays can be modeled with a concrete class.

If you are a listener of the musical work, you have a reference to the script e.g. Bach's 'Fuga and Tocata' and every musician who performs it does it polymorphicaly in her own way.

This is just an example of a possible design (in Java):

public interface Musician {
  public void play(Work work);
}

public interface Work {
  public String getScript();
}

public class FugaAndToccata implements Work {
  public String getScript() {
    return Bach.getFugaAndToccataScript();
  }
}

public class AnnHalloway implements Musician {
  public void play(Work work) {
    // plays in her own style, strict, disciplined
    String script = work.getScript()
  }
}

public class VictorBorga implements Musician {
  public void play(Work work) {
    // goofing while playing with superb style
    String script = work.getScript()
  }
}

public class Listener {
  public void main(String[] args) {
    Musician musician;
    if (args!=null && args.length > 0 && args[0].equals("C")) {
      musician = new AnnHalloway();
    } else {
      musician = new TerryGilliam();
    }
    musician.play(new FugaAndToccata());
}

@Przemek D 2019-01-11 07:26:18

AnnHalloway and VictorBorga feel like they should be objects rather than classes -- your example would read better with eg. public class Pianist implements Musician and victorBorge = new Pianist(); etc.

@Stewart 2009-06-23 08:52:45

Generally speaking, it's the ability to interface a number of different types of object using the same or a superficially similar API. There are various forms:

  • Function overloading: defining multiple functions with the same name and different parameter types, such as sqrt(float), sqrt(double) and sqrt(complex). In most languages that allow this, the compiler will automatically select the correct one for the type of argument being passed into it, thus this is compile-time polymorphism.

  • Virtual methods in OOP: a method of a class can have various implementations tailored to the specifics of its subclasses; each of these is said to override the implementation given in the base class. Given an object that may be of the base class or any of its subclasses, the correct implementation is selected on the fly, thus this is run-time polymorphism.

  • Templates: a feature of some OO languages whereby a function, class, etc. can be parameterised by a type. For example, you can define a generic "list" template class, and then instantiate it as "list of integers", "list of strings", maybe even "list of lists of strings" or the like. Generally, you write the code once for a data structure of arbitrary element type, and the compiler generates versions of it for the various element types.

@tzup 2009-06-23 08:52:12

The term polymorphism comes from:

poly = many

morphism = the ability to change

In programming, polymorphism is a "technique" that lets you "look" at an object as being more than one type of thing. For instance:

A student object is also a person object. If you "look" (ie cast) at the student, you can probably ask for the student ID. You can't always do that with a person, right? (a person is not necessarily a student, thus might not have a student ID). However, a person probably has a name. A student does too.

Bottom line, "looking" at the same object from different "angles" can give you different "perspectives" (ie different properties or methods)

So this technique lets you build stuff that can be "looked" at from different angles.

Why do we use polymorphism? For starters ... abstraction. At this point it should be enough info :)

@Eran Rehavi 2009-06-23 08:22:26

In Object Oriented languages, polymorphism allows treatment and handling of different data types through the same interface. For example, consider inheritance in C++: Class B is derived from Class A. A pointer of type A* (pointer to class A) may be used to handle both an object of class A AND an object of class B.

@Tom Dalling 2009-06-23 08:20:54

Polymorphism is the ability to treat a class of object as if it is the parent class.

For instance, suppose there is a class called Animal, and a class called Dog that inherits from Animal. Polymorphism is the ability to treat any Dog object as an Animal object like so:

Dog* dog = new Dog;
Animal* animal = dog;

@BornToCode 2014-05-05 10:44:27

I wonder how is this related to the (popular) explanation that @Ajay Patel gave classes have different functionality while sharing a common interface

@grokmann 2014-08-08 14:42:36

@BornToCode The parent class is/provides that common interface.

@Shaun Luttin 2017-01-29 01:01:02

Polymorphism does not require subtyping.

@JesperE 2009-06-23 08:18:20

Usually this refers the the ability for an object of type A to behave like an object of type B. In object oriented programming this is usually achieve by inheritance. Some wikipedia links to read more:

EDIT: fixed broken links.

@Artem Barger 2009-06-23 08:27:45

"the ability for an object of type A to behave like an object of type B" - it's not accurate definition. I would say it's more like the ability to treat an object of type A like it's an object of type B.

@JesperE 2009-06-23 08:37:29

Yes. Maybe that is a better phrasing.

@ilya n. 2009-06-29 16:40:03

For completeness, many language implement polymorphism through duck typing, e.g. Python.

@BornToCode 2014-05-05 10:46:43

I wonder how is this related to the (popular) explanation that @Ajay Patel gave classes have different functionality while sharing a common interface

Related Questions

Sponsored Content

25 Answered Questions

[SOLVED] What is the difference between @staticmethod and @classmethod?

39 Answered Questions

17 Answered Questions

34 Answered Questions

[SOLVED] What is the difference between an interface and abstract class?

18 Answered Questions

[SOLVED] Are static class variables possible in Python?

16 Answered Questions

[SOLVED] What are metaclasses in Python?

27 Answered Questions

36 Answered Questions

[SOLVED] What is Inversion of Control?

22 Answered Questions

[SOLVED] When to use self over $this?

  • 2008-09-30 06:23:06
  • Casey Watson
  • 677957 View
  • 1944 Score
  • 22 Answer
  • Tags:   php class oop scope

7 Answered Questions

[SOLVED] What are the differences between type() and isinstance()?

Sponsored Content