多态性-在两个句子中定义

我看过其他的定义和解释,没有一个能让我满意。我想看看是否有人能够在不使用任何代码或示例的情况下,用最多两句话定义多态性。我不想听到“所以你有一个人/车/开罐器...”或者这个词是如何派生出来的(没有人会对你知道聚和变形的意思而感到惊讶)。如果你很好地掌握了什么是多态性,并且很好地掌握了英语,那么你应该能够用一个简短的,尽管密集的定义来回答这个问题。如果您的定义准确地定义了多态性,但是它过于密集,以至于需要几次读取,那么这正是我要寻找的。

为什么只有两句话?因为一个定义是简短而明智的。说明很长,包含示例和代码。在这里可以找到解释(这些页面上的答案对我的问题来说并不令人满意) :

多态性 vs 重写 vs 重载
尽可能简单地描述多态性

我为什么要问这个问题?因为我被问到了同样的问题,我发现我无法给出一个令人满意的定义(以我的标准来看,这是相当高的)。我想看看这个网站上有没有聪明人能做到。

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

95253 次浏览

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.

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

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

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.

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!

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

Multiple forms of a single object is called Polymorphism.

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

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.

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

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

A single class doing different methods is called polymorphism.

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.

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.

Multiple implementations of the same interface.

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

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.

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

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.

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.

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

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

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

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

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.

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.

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.

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

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

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.

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:

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