开发者

Explain polymorphism

What is pol开发者_运维问答ymorphism? 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?


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


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.

Explain polymorphism


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.


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.


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


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.


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.


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 a base class reference that is a derived type, to properly invoke the derived type's 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.


Polymorphism:

  • One method call works on several classes, even if the classes need different implementations;
  • Ability to provide multiple implementations of an action, and to select the correct implementation based on the surrounding context;
  • Provides overloading and overriding;
  • Could occurs both in Runtime and Compile-Time;
      1. Run time Polymorphism : Run time Polymorphism also known as method overriding Method overriding means having two or more methods with the same name , same signature but with different implementation
      1. Compile time Polymorphism : Compile time Polymorphism also known as method overloading Method overloading means having two or more methods with the same name but with different signatures
  • In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. The concept of parametric polymorphism applies to both data types and functions. A function that can evaluate to or be applied to values of different types is known as a polymorphic function. A data type that can appear to be of a generalized type (e.g., a list with elements of arbitrary type) is designated polymorphic data type like the generalized type from which such specializations are made.
  • Disadvantages of Polymorphism:
    • Polymorphism reduces readability of the program. One needs to visualize runtime behaviour of program to identify actual execution time class involved. It also becomes difficult to navigate through classes implementing this concept. Even sofasticated IDEs can not provide this navigation feature. This adds to the maintainance cost to some extent.


Polymorphism - The same object acting differently based on the scenario it is in. For example, if a 12-year old kid was in a room with a bunch of kids, the type of music they would listen to would be different than if a 12 year old kid was in a room full of adults. The 12 year old kid is the same, however the kid acting differently based on the scenario it is in (the different music).


The ability to define a function in multiple forms is called Polymorphism. In C#, Java, C++ there are two types of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).

Overriding: Overriding occurs when a class method has the same name and signature as a method in parent class.

Overloading: Overloading is determined at the compile time. It occurs when several methods have same names with:

  1. Different method signature and different number or type of parameters.
  2. Same method signature but different number of parameters.
  3. Same method signature and same number of parameters but of different type
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜