views:

335

answers:

9

Now can anyone explain polymorphism to me? I'm not sure I am understanding it correctly.

In the Python scope, what I am getting out of it is that I can define parameters as followed:

def blah (x, y)

without having to specify the type, as opposed to another language like Java, where it'd look more along the lines of:

public void blah (int x, string y)

Am I getting that right?

+1  A: 

Yes, that is an example of "type-polymorphism" however when talking about Object Oriented Programming "polymorphism" typically relates to "subtype polymorphism." The example you gave is often called "typing"

Java, C, C++ and others, use static typing. In that, you have to specify the types are compile time.

Python, and ruby use dynamic in that the typing is inferred during interpretation.

Subtype Polymorphism or just "Polymorphism" is the ability for base class reference that a derived type, to properly invoke the derived types method.

For example (in near pseudo code):

class Base
{
  virtual void Draw() { //base draw}
}

class Derived: public Base
{
  void Draw() { //derived draw}
}

Base* myBasePtr = new Derived();

myBasePtr->Draw(); //invokes Derived::Draw(), even though it's a base pointer.

This is polymorphism.

Alan
Actually, in weakly typed languages types are implicitly polymorphic.
Jon Bringhurst
@Jon: perhaps, however python nor ruby are "weakly" typed.
Alan
@Alan: What you described in python is not *duck* typing, it's *dynamic* typing. Duck typing, also called structural typing, means (for object-oriented languages) that objects that have the same type if they have the same methods; the opposite is nominal typing, where objects have the same type if they were created from the same class declaration (i.e. the class name is the same).
Gilles
That's the first time I've ever seen anyone describe C as using strong typing.
Alohci
@Gilles: you are correct.
Alan
@Alohci: C may not offer typesafety and has a multitude of implicit conversions, but you can't willy nilly intermix types.
Alan
It would appear (through a google search) that there are multiple definitions of strong/weak typing. Interesting.
Jon Bringhurst
I think the differentiation you're looking for is not strong vs weak but static typing vs dynamic typing. Static typing has some great benefits when it comes to static analysis of your code--the tools have complete knowledge of your system at any point in time. Dynamic types can change based on runtime context and so can be mutated more easily but make hacking much easier--you can often play some really cute tricks with dynamically typed languages.
Bill K
+4  A: 

Polymorphism literally means "many shapes", and that's pretty good at explaining its purpose. The idea behind polymorphism is that one can use the same calls on different types and have them behave appropriately.

It is important to distinguish this from the typing system - strongly typed languages require that objects be related through an inheritance chain to be polymorphic, but with weakly typed languages, this is not necessary.

In Java (et al.), this is why interfaces are useful - they define the set of functions that can be called on objects without specifying the exact object - the objects that implement that interface are polymorphic with respect to that interface.

In Python, since things are dynamically typed, the interface is less formal, but the idea is the same - calling foo() will succeed on two objects that know how to properly implement foo(), but we don't care about what type they really are.

Matt
@Matt: whether objects have to “be related through an inheritance chain to be polymorphic” is not a matter of strong vs. weak typing, it's a matter of nominal vs. structural subtyping. For example Java has nominal subtyping for classes (`A` is a subclass of `B` if it derives from `B`) but structural subtyping for interfaces (`IA` is a subinterface of `B` if it has at least the same methods). All 8 combinations of strong/weak, static/dynamic, nominal/structural are possible (not to mention mix-and-match).
Gilles
A: 

One Name Multiple Form- Polymerphism

EvilInside
-1 poly (multiple) morph (form) -ism
Ben Aston
I'm sorry, this answer makes no sense.
grifaton
What is Polymerphism?
kirk.burleson
+1  A: 

What you are talking about is auto-typing--or maybe type detection. It is something a Dynamic language tends to do--it allows the user to not know or care about the types at build time--the types are figured out at runtime and not restricted to a specific type.

Polymorphism is where you have two classes that inherit from a main class but each implement a method differently.

For instance, if you have Vehicle as a root class and Car and Bicycle as instances, then vehicle.calculateDistance() would operate based on gas available if the vehicle is an instance of Car, and would operate based on the endurance of the cyclist if it was a Bicycle type.

It's generally used like this:

getTotalDistance(Vehicle[] vehicle) {
    int dist=0
    for each vehicle
        dist+=vehicle.calculateDistance();

Note that you are passing in the base type, but the instances will never be Vehicle itself, but always a child class of Vehicle--but you DO NOT cast it to the child type. Polymorphis means that vehicle morphs into whatever child is required.

Bill K
+2  A: 

No, that is not polymorphism. Polymorphism is the concept that there can be many different implementations of an executable unit and the difference happen all behind the scene without the caller awareness.

For example, Bird and Plane are FlyingObject. So FlyingObject has a method call fly() and both Bird and Plane implement fly() method. Bird and Plan flies differently so the implementations are different. To the clients point of view, it does not matter how Bird or Plane fly, they can just call fly() method to a FlyingObject object does not matter if that object is Plan or Bird.

What you are describing is dynamic and static type checking which the type compatibility is done at run-time and compile-time respectively.

Hope this out. NawaMan

NawaMan
+1  A: 

Short answer: The ability to treat programmatic type instances of different types as the same for certain purposes.

Long answer: From Ancient Greek poly (many) + morph (form) + -ism.

Polymorphism is a general technique enabling different types to be treated uniformly in some way. Examples in the programming world include:

  • parametric polymorphism (seen as generics in Java)
  • subtyping polymorphism, implemented in Java using dynamic message dispatch between object instances.
  • ad-hoc polymorphism, which relates to the ability to define functions of the same name that vary only by the types they deal with (overloading in Java).

The word polymorphism is also used to describe concepts in other, unrelated, domains such as genetics.

Ben Aston
+8  A: 

Beware that different people use different terminology; in particular there is often a rift between the object oriented community and the (rest of the) programming language theory community.

Generally speaking, polymorphism means that a method or function is able to cope with different types of input. For example the add method (or + operator) in the Integer class might perform integer addition, while the add method in the Float class performs floating-point addition, and the add method in the Bignum class performs the correct operations for an arbitrary-size number. Polymorphism is the ability to call the add method on an object without knowing what kind of a number it is.

  • One particular kind of polymorphism, usually called parametric polymorphism in the functional community and generic programming in the OOP community, is the ability to perform certain operations on an object without caring about its precise type. For example, to reverse a list, you don't need to care about the type of the elements of the list, you just need to know that it's a list. So you can write generic (in this sense) list reversal code: it'll work identically on lists of integers, strings, widgets, arbitrary objects, whatever. But you can't write code that adds the elements of a list in a generic way, because the way the elements are interpreted as numbers depends on what type they are.

  • Another kind of polymorphism, usually called ad-hoc polymorphism or (at least for some forms of it) generic programming in the functional community, and often subtyping polymorphism (though this somewhat restricts the concept) in the OOP community, it the ability to have a single method or function that behaves differently depending on the precise type of its arguments (or, for methods, the type of the object whose method is being invoked). The add example above is ad-hoc polymorphism. In dynamically typed languages this ability goes without saying; statically-typed languages tend to (but don't have to) have restrictions such as requiring that the argument be a subclass of some particular class (Addable).

Polymorphism is not about having to specify types when you define a function. That's more related to static vs. dynamic typing, though it's not an intrinsic part of the issue. Dynamically typed languages have no need for type declarations, while statically typed languages usually need some type declarations (going from quite a lot in Java to almost none in ML).

Gilles
+2  A: 

Hope from this example, you will understand what Polymorphism is. In this picture, all objects have a method Speak() but each has a different implementation. Polymorphism allows you to do this, you can declare an action for a class and its subclasses but for each subclass, you can write exactly what you want later.

Polymorphism

Truong Ha
+1  A: 

The answers you've gotten are good, and explain what polymorphism is. I think it can also help to understand some of the reasons it is useful.

In some languages that lack polymorphism you find yourself in situations where you want to perform what is conceptually the same operation on different types of objects, in cases where that operation has to be implemented differently for each type. For instance, in a python-like syntax:

def dosomething(thing):
   if type(thing)==suchandsuch:
      #do some stuff
   elif type(thing)==somesuch:
      #do some other stuff
   elif type(thing)==nonesuch:
      #yet more stuff

There are some problems with this. The biggest is that it causes very tight coupling and a lot of repetition. You are likely to have this same set of tests in a lot of places in your code. What happens if you add a new type that has to support this operation? You have to go find every place you have this sort of conditional and add a new branch. And of course you have to have access to all the source code involved to be able to make those changes. On top of that conditional logic like this is wordy, and hard to understand in real cases.

It's nicer to be able to just write:

thing.dosomething()

On top of being a lot shorter this leads to much looser coupling. This example/explanation is geared to traditional OO languages like Python. The details are a bit different in, say, functional languages. But a lot of the general utility of polymorphism remains the same.

T Duncan Smith