What is "balanced polymorphism?

What is Polymorphism?

  • I was watching a http://www.youtube.com/user/googletechtalks video and they frequently referred to Polymorphism. What is Polymorphism, what is it for, and how is it used?

  • Answer:

    If you think about the Greek roots of the term, it should become obvious. Poly = many: polygon = many-sided, polystyrene = many styrenes, 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, 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. And, 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 :-)

UnkwnTech at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

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.

Ajay Patel

Polymorphism is when you can treat an object as a generic version of something, but 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() { System.Collections.Generic.List<Vehicle> vehicles = new System.Collections.Generic.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 determioned by the sub-class being referenced at runtime. I hope that this helps you.

Antony Gibbs

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: http://en.wikipedia.org/wiki/Polymorphism%5Fin%5Fobject-oriented%5Fprogramming http://en.wikipedia.org/wiki/Polymorphism%5F%28computer%5Fscience%29 EDIT: fixed broken links.

JesperE

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

Vinko Vrsalovic

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;

Tom Dalling

Assuming OOP http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming General Type Polymorphism http://en.wikipedia.org/wiki/Type_polymorphism Most OOP books include sections on this.

Aiden Bell

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 :)

tzup

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()); }

Boris Pavlović

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.

Alex Basson

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.