88

I've looked at other definitions and explanations and none of them satisfy me. I want to see if anybody can define polymorphism in at most two sentences without using any code or examples. I don't want to hear 'So you have a person/car/can opener...' or how the word is derived (nobody is impressed that you know what poly and morph means). If you have a very good grasp of what polymorphism is and have a good command of English than you should be able to answer this question in a short, albeit dense, definition. If your definition accurately defines polymorphism but is so dense that it requires a couple of read overs, then that's exactly what I am looking for.

Why only two sentences? Because a definition is short and intelligent. An explanation is long and contains examples and code. Look here for explanations (the answer on those pages are not satisfactory for my question):

Polymorphism vs Overriding vs Overloading
Try to describe polymorphism as easy as you can

Why am I asking this question ? Because I was asked the same question and I found I was unable to come up with a satisfactory definition (by my standards, which are pretty high). I want to see if any of the great minds on this site can do it.

If you really can't make the two sentence requirement (it's a difficult subject to define) then it's fine if you go over. The idea is to have a definition that actually defines what polymorphism is and doesn't explain what it does or how to use it (get the difference?).

Community
  • 1
  • 1
Mark Testa
  • 929
  • 1
  • 7
  • 8
  • One name, multiple implementation. – Prosunjit Biswas Mar 27 '16 at 21:19
  • 2
    I got asked this question in a job interview. I felt that asking it in a job interview was an elitist act of snobbery, the kind of thing a Google employee would ask smugly supposing that no one could answer it effectively. If you didn't get the job because you couldn't answer, you are probably better off working for people who are more interested in what you can do rather than who you can outwit. – MagicLAMP Apr 23 '17 at 07:15
  • Polymorphism is a very important concept to understand in development. I highly recommend at least understanding its value if not the formal definition. I suggest being able to least explain how the Strategy pattern works and its value. – Chad Johnson May 26 '18 at 13:52
  • I believe this is one very good definition of polymorphism I have read till date that captures the essense of it. Polymorphism is the idea of having mutiple implementation of same abstract concept. It can be static polymorphism as in method overloading and operator overloading or it can be dynamic polymorphism as in method overriding or design pattarsn like strategy pattern. – inquisitive Jan 07 '22 at 23:08

31 Answers31

108

Polymorphism allows the expression of some sort of contract, with potentially many types implementing that contract (whether through class inheritance or not) in different ways, each according to their own purpose. Code using that contract should not(*) have to care about which implementation is involved, only that the contract will be obeyed.

(*) In the ideal case, anyway - obviously quite often the calling code has chosen the appropriate implementation very deliberately!

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Mark, did you at one point accept this answer and then unaccept it? I'm trying to work out what looks like a bug in the reputation system - this answer has given me a net of -15 rep for today, strangely enough. – Jon Skeet Jan 03 '09 at 22:33
  • Same here, Jon - I have now 2 accepted answers with -15 rep. Not that I care but it is intriguing. – Otávio Décio Jan 03 '09 at 22:39
  • ocdecio: Perhaps you could vote for http://stackoverflow.uservoice.com/pages/general/suggestions/97306-rep-limit-still-seems-to-apply-to-accepted-answers ? – Jon Skeet Jan 03 '09 at 22:43
  • @Jon: great, just voted. – Otávio Décio Jan 03 '09 at 22:45
  • Rep system has been crazy lately. There are times in the day when my rep fluctuates wildly, going back and forth around a certain number. Also, a couple of days ago there was a major change in the rep of all the users (cron job?) – Eran Galperin Jan 03 '09 at 22:47
  • @Eran: See blog.stackoverflow.com for the majority of the changes. I think when they fixed the accepted answer stuff it didn't *quite* work. – Jon Skeet Jan 03 '09 at 22:52
  • @Jon: No, I haven't accepted any answers yet. Though it is a very good answer. – Mark Testa Jan 03 '09 at 23:06
  • @Mark: Thanks for the confirmation. That's valuable information. – Jon Skeet Jan 03 '09 at 23:52
  • @Jon: it definitely didn't work. I just had an answer accepted but received no reputation from that. It's not that big of a deal, I just wonder what's really going on – Eran Galperin Jan 04 '09 at 01:56
  • Yeah, rep is bouncing, but always restores. At least, it did for me. – Dykam Nov 14 '09 at 17:26
  • 3
    Strictly speaking, there is no requirement that "one type express some sort of contract". All that is really required is that multiple implementations can respond to the same message without the message sender needing to know or care which implementation is handling the message. – Doug Knesek Nov 16 '09 at 15:20
  • 3
    @Doug: If there's no contract, even implied through documentation or naming, then how on earth do you know it's going to do what you want it to? You talk about an "interface" in your own answer - which sounds very much like a contract to me - what do you see as the difference? Both "interface" and "contract" are words which can be used in a "strong" sense (e.g. enforced at compile-time) or very loosely (e.g. by naming convention and using dynamic typing). – Jon Skeet Nov 16 '09 at 15:26
  • Doug's quite right - it's the "type" in "one *type* to express some sort of contract" that's wrong... as your comment above goes on to acknowledge, there's at least a notional "contract" implied through documentation or naming, but your answer still says the contract's necessarily expressed in a type. In the C++ world for example, that's only true of runtime polymorphism (virtual dispatch). If you eliminated the word "type" from that sentence, the answer would be much improved. – Tony Delroy Nov 07 '13 at 05:02
  • @TonyD: See whether this is any better. – Jon Skeet Nov 07 '13 at 06:45
  • @JonSkeet: looks good - a +1 from me. Cheers. – Tony Delroy Nov 07 '13 at 06:56
  • I would use concept instead of contract and algorithm instead of code. I would rephrase the latter part as follows: "Algorithms utilizing the concept are bound to work with any type satisfying the concept." Perhaps you know a better wording instead of "work". I felt the change is too intrusive to just edit. – Alexander Oh Apr 18 '14 at 18:31
  • 1
    @Alex: Yes, that would be an edit I'd revert - I prefer my wording. You can always add your own answer though. – Jon Skeet Apr 18 '14 at 19:06
76

Fruit can be eaten, as a general rule, but different types of fruit is eaten in different ways. An apple, which is a fruit, can be eaten (because it is a fruit). A banana can also be eaten (because it is also a fruit), but in a different manner from an apple. You peel it first.

Well, at least I do, but I'm weird in some manners so what do I know.

This illustrates inheritance (fruit can be eaten), polymorphism (something that eats fruit can eat all types of fruit), and encapsulation (a banana has a skin).

Seriously though, object inheritance, polymorphism, encapsulation, virtual things, abstract things, private things, public things, these are all hard concepts. If someone absolutely wants to have a 2-sentence definition of this then please tag the question as a code-golf variant, because two such sentences will have to be so terse that unless you know what it is already you won't learn enough about it to know what you need to learn more about.

Dmitry
  • 6,716
  • 14
  • 37
  • 39
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • lassevk: "unless you know what it is already you won't learn enough about it to know what you need to learn more about" << Just to clarify, that's what I am expecting. I'm looking for a definition that may take some thought to understand. Not one that would be used to teach a beginner. – Mark Testa Jan 03 '09 at 23:10
  • 2
    I gathered that, I just posted a somewhat humorous (to me anyway) answer :) Polymorphism and OOP is one of those big wall-things, where if you graph the learning curve, you just hit a big wall and either you crawl over it, or you don't. If you do, then you usually have a big AHA! experience... – Lasse V. Karlsen Jan 04 '09 at 00:17
  • 9
    Hemlock is a fruit too! You can eat it but only once! – James Anderson Apr 07 '09 at 07:02
  • @JamesAnderson So, a singleton? – Lasse V. Karlsen Dec 20 '17 at 21:28
48

Polymorphism is declaring a uniform interface that isn't type aware, leaving implementation details to concrete types that implement the interface.

Eran Galperin
  • 86,251
  • 24
  • 115
  • 132
21

Wikipedia: Polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. Pretty straightforward for me.

Otávio Décio
  • 73,752
  • 17
  • 161
  • 228
21

Actually, there are multiple forms of polymorphism and there is quite some controversy over it; you may even see CS professors who cannot define it properly. I am aware of three types:

  • ad-hoc polymorphism (looks like a duck and walks like a duck => is a duck). Can be seen in Haskell and Python for example.

  • generic polymorphism (where a type is an instance of some generic type). Can be seen in C++ for example (vector of int and vector of string both have a member function size).

  • subtype polymorphism (where a type inherits from another type). Can be seen in most OO programming languages (i.e. Triangle is a Shape).

  • 2
    +1 for mentioning that there are different types of polymorphism. However, your definition of ad-hoc polymorphism seems to be quite different from the one mentioned at http://en.wikipedia.org/wiki/Type_polymorphism . That page says there are 2 types (ad-hoc versus parametric), not 3, and also make a distinction between polymorphic functions and polymorphic data types. Your 3 types, as far as I can determine correspond to parametric polymorphic functions, parametric polymorphic data types, and ad-hoc polymorphic functions, respectively. – Laurence Gonsalves Jul 05 '09 at 22:02
  • hi, what is the difference between "instance of some generic type" and "inherits from another type" these seem to say the same thing? – Shanimal Jul 29 '18 at 22:55
  • @LaurenceGonsalves fwiw, the link provided in the first comment does point to three types. Parametric polymorphism is defined as allowing a function or a data type to be written "generically". – Shanimal Jul 29 '18 at 23:00
16

I really understand, why you are asking this question. I understand polymorphism, but I was at a job interview and was asked to give short and clear definition of polymorphism. Because I couldn't give clear and short definition I started thinking about it and here is my definition:

The ability of objects of one type to have one and the same interface, but different implementation of this interface.

Nikolay Traykov
  • 1,537
  • 17
  • 26
12

Definition:

Polymorphism is a $10 word for a $1 idea - that when I ask for something to be done, I don't care how it is achieved as long as the end result is appropriate. As long as the service is provided correctly, I don't care about the implementation.

Discussion

While it's commonly used in software development, especially in systems developed following object oriented principles, Polymorphism is fundamentally a real world principle and should be defined in real world terms, not technological ones.

Examples

When I want to make a phone call, I pick up a phone, dial a number and talk to the party at the other end. I don't care about who made the phone, what technology it uses, whether it's wired, wireless, mobile or VOIP, or whether it's under warranty.

When I want to print a document, I print it. I don't care about the implementation language, brand of printer, style of connection, choice of consumable or quality of paper.

Bevan
  • 43,618
  • 10
  • 81
  • 133
  • 5
    sound like example of `Encapsulation` to me – Singleton Dec 16 '10 at 19:01
  • 1
    Polymorphism, Encapsulation and Abstraction are all pretty closely related, though they focus on different perspectives. Good abstractions make polymorphism easier to achieve, and good encapsulation helps to prevent details "leaking". – Bevan Dec 16 '10 at 21:47
11

Multiple implementations of the same interface.

Example: Many models of telephone implement the numeric keypad interface.

Doug Knesek
  • 6,527
  • 3
  • 21
  • 26
8

Polymorphism is a object oriented strategy used when designing object models, to help simplify the code. At it's core polymorphism is the ability to define two simillar yet different objects, and to then treat the two objects as if they are the same.

Ok that's hard....

JoshBerke
  • 66,142
  • 25
  • 126
  • 164
7

I just thought I'd add my own interpretation of what polymorphism is: Very generically, polymorphism is the act of providing a single interface to entities of different types.

That's rather generic, but that's the only way I can think of to wrap all three types of polymorphisms I know about: ad hoc, parametric and subtype. I'll go in more details below, and have sorted polymorphism types by name, alphabetically. The one you're interested on is most probably subtype polymorphism, which is the last one.

Ad hoc polymorphism

Ad hoc polymorphism is the act of providing multiple implementations of the same method for different parameter types. In OOP, it's generally known as method overloading. For example:

public String format(int a) {
    return String.format("%2d", a);
}

public String format(Date a) {
    return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(a);
}

Both format methods share a single interface, but they work on entities of different types.

Parametric polymorphism

Parametric polymorphism is the act of making a class (or method) work on a type that is itself a parameter of the class (or method). It's often referred to as generics.

For example, Java's List[T] expects a parameter T at instantiation time, and this parameter defines the type of the resulting object.

Note for purists that I'm purposefully ignoring raw types as I feel they'd just muddy the waters in this context.

List[String] and List[Date] share a single interface, but work on (and are) different types.

Subtype polymorphism

Subtype polymorphism is probably what you initially meant in your question: It's the act of providing a single interface to multiple implementations of the same type.

To use the customary example: Animal provides a contract that all implementations must respect. Dog is an Animal, and as such supports all operations that Animal declares. According to the Liskov substitution principle, this allows you to use an instance of Dog where an instance of Animal is expected (but not the other way around).

If Cat and Dog are both subclasses of Animal, then they share a single interface but are in fact different types.

I'm going off in a bit of a tangent here, but subtype polymorphism is (I think) the only one that allows overriding: the act of redefining the behaviour of a method defined by a parent class. This is often confused with overloading which, as we saw before, is a type of polymorphism and doesn't in fact need subclassing (nor does it need classes, really).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nicolas Rinaudo
  • 6,068
  • 28
  • 41
  • so what about interface based polymorphism ? – siamak Oct 21 '14 at 00:09
  • @siamak is that not just a specific kind of subtype polymorphism where the parent type is entirely abstract? Or do you mean something else? – Nicolas Rinaudo Oct 21 '14 at 07:45
  • My intention of interface is Interface as a Reference Type that exists in Object Oriented languages,like this: Interface I1{void M();} I do believe that There are so many differences between subtype or Inheritance-Based Polymorphism and Interface-Based Polymorphism . Because there is an "Is-a" relationship in Inheritance-based polymorphism between types but there is not such a thing in Interface-baced polymorphism. In fact a same behavior with different implementations could be shared between various different Types (Classes) – siamak Oct 21 '14 at 11:15
  • I must admit I'm confused - aside from your somewhat ballistic approach to upper-casing, it seems that your description of what you call interface based polymorphism is precisely the same as my description of subtype polymorphism. I'm sure you see a difference, but I'm afraid it really isn't clear to me. – Nicolas Rinaudo Oct 21 '14 at 11:24
  • As you can see there is no relationship between car and bird and person but they can move in their own way . There is tremendous difference between Abstract class and Interface and using interface is not the same as subtyping, so in my opinion inheritance polymorphism and interface based polymorphism are not the same things and are not equal. //its hard, coding in comments segment// – siamak Oct 21 '14 at 12:56
  • Sorry for the mess in the comments, at the first time I just focused to response you under your comment, Now I update my answer with a simple code to show what I meant by interfaces-Based polymorphism.I deleted my previous code based comments and add an update section in my answer,please take a look at it. – siamak Oct 22 '14 at 20:56
6

It seems that the best definitions are provided here, so let me add my two cents please, just for other observers. I hope it could help more.

There are two kinds of polymorphism:

1. Compile-time (static) polymorphism or (ad hoc) polymorphism.

That is simply method overloading and operator overloading

2.  Run time or (dynamic) polymorphism.

The first term is inherited from the Java and C++ terminology.

But in the .NET terminology only the second one (I mean run time polymorphism) is really supposed as polymorphism and simply called polymorphism.

And as far as I know there are three methods for implementing (run time) polymorphism.

 1. Parametric polymorphism or simply the use of generics (templates in C++).

 2. Inheritance-based polymorphism or subtyping.

 3. Interface-based polymorphism.

A simple example Of interface-based polymorphism:

interface Imobile
{
    void Move();
}

class Person :Imobile
{
    public void Move() { Console.WriteLine("I am a person and am moving in my way."); }
}

class Bird :Imobile
{
    public void Move() { Console.WriteLine("I am a bird and am moving in my way."); }
}

class Car :Imobile
{
    public void Move() { Console.WriteLine("I am a car and am moving in my way."); }
}


class Program
{

    static void Main(string[] args)
    {
        // Preparing a list of objects
        List<Imobile> mobileList = new List<Imobile>();

        mobileList.Add(new Person());
        mobileList.Add(new Bird());
        mobileList.Add(new Car());

        foreach (Imobile mobile in mobileList)
        {
            mobile.Move();
        }

        // Keep the console open
        Console.WriteLine("Press any key to exit the program:");
        Console.ReadKey();
    }
}

Output:

 I am a person and am moving in my way.
 I am a bird and am moving in my way.
 I am a car and am moving in my way.
 Press any key to exit the program:
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
siamak
  • 669
  • 1
  • 10
  • 28
  • I still don't see the difference you make. Person, Bird and Car are all subtypes of Imobile. Person is an Imobile, Bird is an Imobile and Car is an Imobile. If you were to require a variable of type Imobile, you could use either an instance of Person, Bird or Car, all would type check. That is precisely what subtype polymorphism means. – Nicolas Rinaudo Oct 22 '14 at 21:01
  • Bird and Person and Car are not subtypes of Imobile, they are Implementers of that Interface and "Realize" that Interface in their own way ,The term of "subtype" is widely used between a real Type and a real subtype that inherited from it ,and in this situation there is an "Is-a" relationship between them, for example a dog is subtype of a mammal. – siamak Oct 22 '14 at 22:00
  • from the compiler point of view making a reference to an interface and using the references is something true and correct. /BUT/ IT is not an equal concept with subtyping in an inheritance relationship. And I think calling the Implementers of an interface as subtypes is so awkward and really not true. – siamak Oct 22 '14 at 22:01
  • An example of Inheritance-based polymorphism would do well to expound on this answer. – Marcelo Mason Mar 17 '17 at 17:52
6

polymorphism == multiple classes + same method signatures + class-specific behavior.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
5

Polymorphism is a software coding abstraction where several different underlying entities (usually data, but nit always) all share a common interface which allows them to look and act identical at runtime. We use this as a development technique to enforce consistent behavior over a wide range of similar, but not identical instances with an absolute minimal implementation, thus reducing the expectation for bugs and inconsistencies.

Paul.

Paul W Homer
  • 2,728
  • 1
  • 19
  • 25
2

Polymorphism is a feature of programming languages that allows an object to be treated as an instance of its supertype.

TarkaDaal
  • 18,798
  • 7
  • 34
  • 51
2

Multiple forms of a single object is called Polymorphism.

milot
  • 1,060
  • 2
  • 8
  • 17
2

Polymorphism

Different objects can respond to the same message in different ways, enable objects to interact with one another without knowing their exact type.

Via: http://www.agiledata.org/essays/objectOrientation101.html

2

Polymorphism is ability of an object to appear and behave differently for the same invocation. ex: each animal appear and sound differently ( when you hit it :) )

Mallik
  • 21
  • 1
1

This is the definition that I've always followed:

Two objects are polymorphic (with respect to a particular protocol) between them, if both respond to the same messages with the same semantic.

Polymorphism is about messages, is about being able to respond the same set of messages with the same semantic.

If two object CAN respond to empty? but the semantic of the message is different, then.. they are not polymorphic.

Claudio Acciaresi
  • 31,951
  • 5
  • 33
  • 43
1

Polymorphism at the lower level is the ability to invoke methods that are defined by the implementors of an interface from the interface instance.

Igor Zevaka
  • 74,528
  • 26
  • 112
  • 128
1

Polymorphism is a programming feature that allows an object to have many types ('shapes') and lets you treat it as any of those types depending on what you need to do without knowing or caring about its other types.

Jeff Sternal
  • 47,787
  • 8
  • 93
  • 120
1

Giving a single name to a set of analogous operations on different types. When done well, the analogy is obvious e.g. "adding" numbers arithmetically and "adding" strings by concatenation (which sums their lengths).

joel.neely
  • 30,725
  • 9
  • 56
  • 64
1

Polymorphism is language functionality allowing high-level algorithmic code to operate unchanged on multiple types of data. And the other sentence, whatever it was for... ;-P.

( The types C++ supports are listed and contrasted in my answer: Polymorphism in c++ )

Community
  • 1
  • 1
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
0

Entities of the same type (that is, implemented same interface or derived from same class), behave in different ways (under same method name).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
paul paul
  • 93
  • 1
  • 5
0

Polymorphism concept became a phenomenon lately. Here is the actual drift. Runtime defines which submethod should be invoked by a reference of a super class. Now, what does mean in practice? It means actually nothing. You can code simply without polymorphism. So, why? Because, if we haven't got the polymorphism, we had to memorize all the subclass functions definitions. Polymorphism saves us from this in practice.

You can define a list as follows:

List list = new List();

but if you check for IList, you can benefit of the interface as:

IList list = new List();

and use the IList reference freely. Assuming IList is also implemented in another class, you can use methods of that unknown class via again IList reference without trying to remember that class name. Marvelous, isn't it?

Now, more valuable information is coming:
Java is by default polymorphic, whereas .NET and C++ are not, in MS, you have to declare the base function virtual (and in .NET override keyword).

Also, there are 2 integral rules in polymorphism. One is inheritance (via interface impl. or via class extending) and the other is overriding. Without overriding, polymorphism doesn't exist. Note that method overloading (which always in a single class) is also a type of "minimalistic" polymorphism.

andr
  • 15,970
  • 10
  • 45
  • 59
0

I think implementation of methods of the same signature in different classes (having some sort of inheritance relation either using extends or implements) is method overriding and also polymorphism because in this way we are achieving many forms of the same method signature.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
anand
  • 1
0

For a given method signature, different method implementations are run for different, hierarchically related, classes.

Paolo
  • 2,461
  • 5
  • 31
  • 45
0

Polymorphism is the ability of using different classes that implement a common interface (or extend a common base class) in a common way, without needing to now the specific implementation, and using only the methods available in the common interface.

Ie: In Java, as ArrayList and LinkedList both implement List, if you declare a variable as List, you can always perform the operations allowed in List, no matter which if you variable was instanced as an ArrayList or a LinkedList.

GaRRaPeTa
  • 5,459
  • 4
  • 37
  • 61
-2

I guess sometimes objects are dynamically called. You are not sure whether the object would be a triangle, square etc in a classic shape poly. example.

So, to leave all such things behind, we just call the function of derived class and assume the one of the dynamic class will be called.

You wouldn't care if its a sqaure, triangle or rectangle. You just care about the area. Hence the getArea method will be called depending upon the dynamic object passed.

Kapil D
  • 2,662
  • 6
  • 28
  • 30
-2

Polymorphism is the ability of a function to automatically adapt to accept input data of different data types. You can 'Add' two doubles '1.1' and '2.2' and get '3.3' or 'Add' two strings "Stack" and "Overflow" and get "StackOverflow".

J-Dizzle
  • 4,861
  • 4
  • 40
  • 50
  • Why did someone mark this down - this is the 'literal answer' from National Instrument's web page on polymorphism!!! – J-Dizzle Aug 29 '15 at 00:21
-3

Polymorphism is when different objects respond to the same method in a different way. For example, a car moves on the road while a person walks on the road. Those are two objects responding to the same road in a different way.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Actually, polymorphism is seeing instances of different classes as a common type, and been able to use the methods declared in this common type independently of how the different classes implement those methods. – GaRRaPeTa Sep 16 '14 at 19:58
-5

A single class doing different methods is called polymorphism.