什么是多态,它是什么,以及它是如何使用的?

时间:2021-09-27 16:02:32

I was watching a Google Tech Talks video, and they frequently referred to polymorphism.

我正在观看Google Tech Talks视频,他们经常提到多态性。

What is polymorphism, what is it for, and how is it used?

什么是多态,它是什么,以及它是如何使用的?

27 个解决方案

#1


If you think about the Greek roots of the term, it should become obvious.

如果你考虑这个术语的希腊词根,它应该变得明显。

  • Poly = many: polygon = many-sided, polystyrene = many styrenes (a), polyglot = many languages, and so on.
  • Poly = many:polygon = many-sided,polystyrene = many styrenes(a),polyglot = many languages,依此类推。

  • Morph = change or form: morphology = study of biological form, Morpheus = the Greek god of dreams able to take any form.
  • 形态=变化或形式:形态=研究生物形态,Morpheus =希腊梦之神能够采取任何形式。

So polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types).

因此,多态性是(在编程中)为不同的底层形式(数据类型)呈现相同的接口的能力。

For example, in many languages, 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.

但是,以同样的方式,像BigDecimal或Rational或Imaginary这样的类也可以提供这些操作,即使它们在不同的数据类型上运行。

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

经典的例子是Shape类和所有可以从它继承的类(方形,圆形,十二面体,不规则多边形,splat等)。

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.

使用多态,这些类中的每一个都将具有不同的底层数据。点形状只需要两个坐标(假设它当然在二维空间中)。圆圈需要一个圆心和半径。正方形或矩形需要两个坐标用于左上角和右下角以及(可能)旋转。不规则多边形需要一系列线条。

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:

通过使类负责其代码及其数据,您可以实现多态。在这个例子中,每个类都有自己的Draw()函数,客户端代码可以简单地执行:

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

这与代码与数据分离的旧方法形成对比,并且您将拥有诸如drawSquare()和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 :-)

面向对象,多态和继承都是密切相关的概念,它们对于了解至关重要。在我漫长的职业生涯中,有很多“银子弹”基本上刚刚失败,但OO范例已经证明是一个很好的。学习它,理解它,喜欢它 - 你会很高兴你做到了:-)


(a) I originally wrote that as a joke but it turned out to be correct and, therefore, not that funny. The momomer styrene happens to be made from carbon and hydrogen, C8H8, and polystyrene is made from groups of that, (C8H8)n.

(a)我最初把它写成一个笑话,但事实证明它是正确的,因此,并不那么有趣。单体苯乙烯恰好由碳和氢制成,C8H8,聚苯乙烯由(C8H8)n的基团制成。

Perhaps I should have stated that a polyp was many occurrences of the letter p although, now that I've had to explain the joke, even that doesn't seem funny either.

也许我应该说息肉是字母p的多次出现,虽然现在我不得不解释这个笑话,即使这看起来也不好笑。

Sometimes, you should just quit while you're behind :-)

有时,你应该在你落后时退出:-)

#2


Polymorphism is when you can treat an object as a generic version of something, but when 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:

这是C#中的一个例子。在控制台应用程序中创建四个类:

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:

现在在控制台应用程序的模块的Main()中创建以下内容:

public void Main()
{
    List<Vehicle> vehicles = new 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.

在这个例子中,我们创建了一个基类Vehicle的列表,它不知道每个子类有多少个*,但是知道每个子类负责知道它有多少个*。

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.

接下来,我们可以循环遍历列表中的每个Vehicle,并对它们进行相同的处理,但是当我们访问每个Vehicle'Wheels'属性时,Vehicle类将该代码的执行委托给相关的子类。

This code is said to be polymorphic, as the exact code which is executed is determined by the sub-class being referenced at runtime.

该代码被称为多态的,因为执行的确切代码由运行时引用的子类确定。

I hope that this helps you.

我希望这对你有所帮助。

#3


From Understanding and Applying Polymorphism in PHP, Thanks Steve Guidetti.

从理解和应用PHP中的多态性,感谢Steve Guidetti。

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.

在编程领域,多态性用于使应用程序更加模块化和可扩展。您可以根据需要创建可互换的对象,而不是描述不同操作过程的混乱条件语句。这是多态性的基本目标。

#4


If anybody says CUT to these people

如果有人对这些人说过CUT

  1. The Surgeon
  2. The Hair Stylist
  3. 发型师

  4. The Actor

What will happen?

会发生什么?

  • The Surgeon would begin to make an incision.
  • 外科医生会开始做切口。

  • The Hair Stylist would begin to cut someone's hair.
  • 发型师会开始剪掉某人的头发。

  • The Actor would abruptly stop acting out of the current scene, awaiting directorial guidance.
  • 演员将突然停止在当前场景中行动,等待导演指导。

So above representation shows What is polymorphism (same name, different behavior) in OOP.

所以上面的表示显示了OOP中的多态(同名,不同行为)是什么。

If you are going for an interview and interviewer asks you tell/show a live example for polymorphism in the same room we are sitting at, say-

如果你要去面试并且面试官要求你告诉/展示我们所在的同一个房间的多态性的实例,比如说 -

Answer - Door / Windows

答案 - 门/窗

Wondering How?

Through Door / Window - a person can come, air can come, light can come, rain can come, etc.

通过门/窗 - 一个人可以来,空气可以来,光可以来,雨可以来,等等。

To understand it better and in a simple manner I used above example.. If you need reference for code follow above answers.

为了更好地理解它,并以简单的方式使用上面的例子..如果你需要参考代码,请按照上面的答案。

#5


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:

例如,假设有一个名为Animal的类,以及一个名为Dog的类,它继承自Animal。多态性是将任何Dog对象视为Animal对象的能力,如下所示:

Dog* dog = new Dog;
Animal* animal = dog;

#6


Polymorphism:

It is the concept of object oriented programming.The ability of different objects to respond, each in its own way, to identical messages is called polymorphism.

它是面向对象编程的概念。不同对象以自己的方式响应相同消息的能力称为多态。

Polymorphism results from the fact that every class lives in its own namespace. The names assigned within a class definition don’t conflict with names assigned anywhere outside it. This is true both of the instance variables in an object’s data structure and of the object’s methods:

多态性源于每个类都在其自己的命名空间中。在类定义中指定的名称与在其外部任何位置分配的名称不冲突。这对象的数据结构和对象方法中的实例变量都是如此:

  • Just as the fields of a C structure are in a protected namespace, so are an object’s instance variables.

    就像C结构的字段在受保护的命名空间中一样,对象的实例变量也是如此。

  • Method names are also protected. Unlike the names of C functions, method names aren’t global symbols. The name of a method in one class can’t conflict with method names in other classes; two very different classes can implement identically named methods.

    方法名称也受到保护。与C函数的名称不同,方法名称不是全局符号。一个类中的方法名称不能与其他类中的方法名称冲突;两个非常不同的类可以实现具有相同名称的方法。

Method names are part of an object’s interface. When a message is sent requesting that an object do something, the message names the method the object should perform. Because different objects can have methods with the same name, the meaning of a message must be understood relative to the particular object that receives the message. The same message sent to two different objects can invoke two distinct methods.

方法名称是对象接口的一部分。当发送消息请求对象执行某些操作时,该消息将命名该对象应执行的方法。因为不同的对象可以具有相同名称的方法,所以必须相对于接收消息的特定对象来理解消息的含义。发送到两个不同对象的相同消息可以调用两个不同的方法。

The main benefit of polymorphism is that it simplifies the programming interface. It permits conventions to be established that can be reused in class after class. Instead of inventing a new name for each new function you add to a program, the same names can be reused. The programming interface can be described as a set of abstract behaviors, quite apart from the classes that implement them.

多态的主要好处是它简化了编程接口。它允许建立可以在课堂上重复使用的约定。您可以重复使用相同的名称,而不是为添加到程序中的每个新函数创建新名称。编程接口可以描述为一组抽象行为,与实现它们的类完全不同。

Examples:

Example-1: Here is a simple example written in Python 2.x.

示例1:这是一个用Python 2.x编写的简单示例。

class Animal:
    def __init__(self, name):    # Constructor of the class
        self.name = name
    def talk(self):              # Abstract method, defined by convention only
        raise NotImplementedError("Subclass must implement abstract method")

class Cat(Animal):
    def talk(self):
        return 'Meow!'

class Dog(Animal):
    def talk(self):
        return 'Woof! Woof!'

animals = [Cat('Missy'),
           Dog('Lassie')]

for animal in animals:
    print animal.name + ': ' + animal.talk()

Example-2: Polymorphism is implemented in Java using method overloading and method overriding concepts.

示例2:使用方法重载和方法覆盖概念在Java中实现多态性。

Let us Consider Car example for discussing the polymorphism. Take any brand like Ford, Honda, Toyota, BMW, Benz etc., Everything is of type Car.

让我们考虑Car讨论多态性的例子。选择福特,本田,丰田,宝马,奔驰等品牌,一切都是汽车类型。

But each have their own advanced features and more advanced technology involved in their move behavior.

但每个都有自己的先进功能和更先进的技术参与其移动行为。

Now let us create a basic type Car

现在让我们创建一个基本类型的汽车

Car.java

public class Car {

    int price;
    String name;
    String color;

    public void move(){
    System.out.println("Basic Car move");
    }

}

Let us implement the Ford Car example.

让我们实施福特汽车的例子。

Ford extends the type Car to inherit all its members(properties and methods).

福特扩展了Car类型以继承其所有成员(属性和方法)。

Ford.java

public class Ford extends Car{
  public void move(){
    System.out.println("Moving with V engine");
  }
}

The above Ford class extends the Car class and also implements the move() method. Even though the move method is already available to Ford through the Inheritance, Ford still has implemented the method in its own way. This is called method overriding.

上面的Ford类扩展了Car类,并且还实现了move()方法。尽管福特通过继承已经可以使用移动方法,但福特仍然以自己的方式实施了该方法。这称为方法覆盖。

Honda.java

public class Honda extends Car{
  public void move(){
    System.out.println("Move with i-VTEC engine");
  }
}

Just like Ford, Honda also extends the Car type and implemented the move method in its own way.

就像福特一样,本田也扩展了Car类型并以自己的方式实现了移动方法。

Method overriding is an important feature to enable the Polymorphism. Using Method overriding, the Sub types can change the way the methods work that are available through the inheritance.

方法覆盖是启用多态性的重要特征。使用方法覆盖,Sub类型可以通过继承更改方法的工作方式。

PolymorphismExample.java

public class PolymorphismExample {
  public static void main(String[] args) {
    Car car = new Car();
    Car f = new Ford();
    Car h = new Honda();

    car.move();
    f.move();
    h.move();

  }
}

Polymorphism Example Output:

多态性示例输出:

In the PolymorphismExample class main method, i have created three objects- Car, Ford and Honda. All the three objects are referred by the Car type.

在PolymorphismExample类主方法中,我创建了三个对象 - 汽车,福特和本田。所有三个对象都由Car类型引用。

Please note an important point here that A super class type can refer to a Sub class type of object but the vice-verse is not possible. The reason is that all the members of the super class are available to the subclass using inheritance and during the compile time, the compiler tries to evaluate if the reference type we are using has the method he is trying to access.

请注意这里的重点是超类类型可以引用Sub类类型的对象,但反之亦然。原因是超类的所有成员都可以使用继承来使用子类,并且在编译期间,编译器会尝试评估我们使用的引用类型是否具有他试图访问的方法。

So, for the references car,f and h in the PolymorphismExample, the move method exists from Car type. So, the compiler passes the compilation process without any issues.

因此,对于PolymorphismExample中的引用car,f和h,移动方法存在于Car类型中。因此,编译器通过编译过程没有任何问题。

But when it comes to the run time execution, the virtual machine invokes the methods on the objects which are sub types. So, the method move() is invoked from their respective implementations.

但是当涉及运行时执行时,虚拟机会调用作为子类型的对象的方法。因此,方法move()从它们各自的实现中调用。

So, all the objects are of type Car, but during the run time, the execution depends on the Object on which the invocation happens. This is called polymorphism.

因此,所有对象都是Car类型,但在运行时,执行依赖于调用发生的Object。这称为多态性。

#7


Simple Explanation by analogy

The President of the United States employs polymorphism. How? Well, he has many advisers:

美国总统采用多态性。怎么样?好吧,他有很多顾问:

  1. Military Advisers
  2. Legal Advisers
  3. Nuclear physicists (as advisers)
  4. 核物理学家(顾问)

  5. Medical advisers
  6. etc etc.

Everyone Should only be responsible for one thing: Example:

每个人都应该对一件事负责:例如:

The president is not an expert in zinc coating, or quantum physics. He doesn't know many things - but he does know only one thing: how to run the country.

总统不是锌涂层或量子物理专家。他不知道很多事情 - 但他只知道一件事:如何管理这个国家。

It's kinda the same with code: concerns and responsibilities should be separated to the relevant classes/people. Otherwise you'd have the president knowing literally everything in the world - the entire Wikipedia. Imagine having the entire wikipedia in a class of your code: it would be a nightmare to maintain.

它与代码有点相同:关注点和责任应该与相关的类/人分开。否则你会让总统知道世界上的一切 - 整个*。想象一下,将整个*放在一个代码类中:维护它将是一场噩梦。

Why is that a bad idea for a president to know all these specific things?

为什么总统要知道所有这些具体的事情是个坏主意?

If the president were to specifically tell people what to do, that would mean that the president needs to know exactly what to do. If the president needs to know specific things himself, that means that when you need to make a change, then you'll need to make it in two places, not just one.

如果总统要专门告诉人们该做什么,那就意味着总统需要知道该做什么。如果总统需要自己了解具体事情,那就意味着当你需要做出改变时,你需要在两个地方做到,而不仅仅是一个。

For example, if the EPA changes pollution laws then when that happens: you'd have to make a change to the EPA Class and also the President class. Changing code in two places rather than one can be dangerous - because it's much harder to maintain.

例如,如果环保署改变了污染法律,那么当发生这种情况时:你必须改变EPA班级和总统班级。在两个地方而不是一个地方更改代码可能很危险 - 因为维护起来要困难得多。

Is there a better approach?

有更好的方法吗?

There is a better approach: the president does not need to know the specifics of anything - he can demand the best advice, from people specifically tasked with doing those things.

有一种更好的方法:总统不需要知道任何事情的具体细节 - 他可以要求那些专门负责这些事情的人提供最好的建议。

He can use a polymorphic approach to running the country.

他可以使用多态方法来运行这个国家。

Example - of using a polymorphic approach:

示例 - 使用多态方法:

All the president does is ask people to advise him - and that's what he actually does in real life - and that's what a good president should do. his advisors all respond differently, but they all know what the president means by: Advise(). He's got hundreds of people streaming into his office. It doesn't actually matter who they are. All the president knows is that when he asks them to "Advise" they know how to respond accordingly:

总统所做的就是要求人们为他提供建议 - 而这正是他在现实生活中所做的事情 - 这就是一位优秀的总统应该做的事情。他的顾问都有不同的反应,但他们都知道总统的意思:建议()。他有数百人涌入他的办公室。实际上他们是谁并不重要。所有总统都知道,当他要求他们“建议”时,他们知道如何做出相应的回应:

public class MisterPresident
{
    public void RunTheCountry()
    {
        // assume the Petraeus and Condi classes etc are instantiated.
        Petraeus.Advise(); // # Petraeus says send 100,000 troops to Fallujah
        Condolezza.Advise(); // # she says negotiate trade deal with Iran
        HealthOfficials.Advise(); // # they say we need to spend $50 billion on ObamaCare
    }
}

This approach allows the president to run the country literally without knowing anything about military stuff, or health care or international diplomacy: the details are left to the experts. The only thing the president needs to know is this: "Advise()".

这种方法允许总统在不知道军事资料,医疗保健或国际外交的情况下从字面上管理国家:详细信息留给专家。总统唯一需要知道的是:“建议()”。

What you DON"T want:

你想要什么:

public class MisterPresident
{
    public void RunTheCountry()
    {
        // people walk into the Presidents office and he tells them what to do
        // depending on who they are.

        // Fallujah Advice - Mr Prez tells his military exactly what to do.
        petraeus.IncreaseTroopNumbers();
        petraeus.ImproveSecurity();
        petraeus.PayContractors();

        // Condi diplomacy advice - Prez tells Condi how to negotiate

        condi.StallNegotiations();
        condi.LowBallFigure();
        condi.FireDemocraticallyElectedIraqiLeaderBecauseIDontLikeHim();

        // Health care

        healthOfficial.IncreasePremiums();
        healthOfficial.AddPreexistingConditions();
    }
}

NO! NO! NO! In the above scenario, the president is doing all the work: he knows about increasing troop numbers and pre-existing conditions. This means that if middle eastern policies change, then the president would have to change his commands, as well as the Petraeus class as well. We should only have to change the Petraeus class, because the President shouldn't have to get bogged down in that sort of detail. He doesn't need to know about the details. All he needs to know is that if he makes one order, everything will be taken care of. All the details should be left to the experts.

没有!没有!没有!在上述情景中,总统正在做所有的工作:他知道增加部队数量和预先存在的条件。这意味着,如果中东政策发生变化,总统将不得不改变他的命令,以及彼得雷乌斯班。我们只需改变彼得雷乌斯班,因为总统不应该陷入这种细节的困境。他不需要知道细节。他需要知道的是,如果他订购了一份订单,那么一切都将得到妥善处理。所有细节都应留给专家。

This allows the president to do what he does best: set general policy, look good and play golf :P.

这使得总统可以做他最擅长的事情:制定一般政策,看起来很好并打高尔夫:P。

How is it actually implemented - through a base class or a common interface

That in effect is polymorphism, in a nutshell. How exactly is it done? Through "implementing a common interface" or by using a base class (inheritance) - see the above answers which detail this more clearly. (In order to more clearly understand this concept you need to know what an interface is, and you will need to understand what inheritance is. Without that, you might struggle.)

简而言之,这实际上是多态性。究竟是怎么做到的?通过“实现通用接口”或使用基类(继承) - 请参阅上面的答案,这些答案更清楚地详述了这一点。 (为了更清楚地理解这个概念,你需要知道接口是什么,你需要了解继承是什么。没有它,你可能会很困难。)

In other words, Petraeus, Condi and HealthOfficials would all be classes which "implement an interface" - let's call it the IAdvisor interface which just contains one method: Advise(). But now we are getting into the specifics.

换句话说,Petraeus,Condi和HealthOfficials都将是“实现接口”的类 - 让我们称之为IAdvisor接口,它只包含一个方法:Advise()。但现在我们正在深入了解细节。

This would be ideal

这将是理想的

    public class MisterPresident
    {
            // You can pass in any advisor: Condi, HealthOfficials, Petraeus etc. The president has no idea who it will be. But he does know that he can ask them to "advise" and that's all Mr Prez cares for.
        public void RunTheCountry(IAdvisor governmentOfficer)
        {             
            governmentOfficer.Advise();              
        }
    }


    public class USA
    {
        MisterPresident president;

        public USA(MisterPresident president)
        {
            this.president = president;
        }

        public void ImplementPolicy()
        {
            IAdvisor governmentOfficer = getAdvisor(); // Returns an advisor: could be condi, or petraus etc.
            president.RunTheCountry(governmentOfficer);
        }
    }

Summary

All that you really need to know is this:

你真正需要知道的是:

  • The president doesn't need to know the specifics - those are left to others.
  • 总统不需要知道具体细节 - 这些细节留给其他人。

  • All the president needs to know is to ask who ever walks in the door to advice him - and we know that they will absolutely know what to do when asked to advise (because they are all in actuality, advisors (or IAdvisors :) )
  • 所有总统需要知道的是询问谁走进门给他建议 - 我们知道他们在被要求提出建议时绝对知道该怎么做(因为他们都是实际的,顾问(或IAdvisors :))

I really hope it helps you. If you don't understand anything post a comment and i'll try again.

我真的希望它对你有所帮助。如果你发表任何评论都不明白,我会再试一次。

#8


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:

通常,这指的是类型A的对象的行为类似于B类对象的能力。在面向对象的编程中,这通常通过继承来实现。一些*链接阅读更多:

EDIT: fixed broken links.

编辑:修复断开的链接。

#9


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

你可以通过一个杯子而不是一个特定的实例。这有助于实现一般性,因为您不必为每种杯子类型提供特定的measure()实例

#10


I know this is an older question with a lot of good answers but I'd like to include a one sentence answer:

我知道这是一个较老的问题,有很多好的答案,但我想包括一句话答案:

Treating a derived type as if it were it's base type.

处理派生类型,就好像它是基类型一样。

There are plenty of examples above that show this in action, but I feel this is a good concise answer.

上面有很多例子说明了这一点,但我觉得这是一个很简洁的答案。

#11


(I was browsing another article on something entirely different.. and polymorphism popped up... Now I thought that I knew what Polymorphism was.... but apparently not in this beautiful way explained.. Wanted to write it down somewhere.. better still will share it... )

(我正在浏览关于完全不同的东西的另一篇文章......并且多态性突然出现......现在我以为我知道多态性是什么......但显然不是以这种美妙的方式解释的......想要把它写在某处......更好还是会分享...)

http://www.eioba.com/a/1htn/how-i-explained-rest-to-my-wife

read on from this part:

请阅读本部分:

..... polymorphism. That's a geeky way of saying that different nouns can have the same verb applied to them.

.....多态性。这是一种令人讨厌的说法,即不同的名词可以使用相同的动词。

#12


The term polymorphism comes from:

术语多态性来自:

poly = many

poly =很多

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

为什么我们使用多态?对于初学者......抽象。在这一点上它应该是足够的信息:)

#13


Generally speaking, it's the ability to interface a number of different types of object using the same or a superficially similar API. There are various forms:

一般来说,它是使用相同或表面上类似的API来连接许多不同类型的对象的能力。有各种形式:

  • Function overloading: defining multiple functions with the same name and different parameter types, such as sqrt(float), sqrt(double) and sqrt(complex). In most languages that allow this, the compiler will automatically select the correct one for the type of argument being passed into it, thus this is compile-time polymorphism.

    函数重载:定义具有相同名称和不同参数类型的多个函数,例如sqrt(float),sqrt(double)和sqrt(complex)。在大多数允许这种情况的语言中,编译器会自动为传递给它的参数类型选择正确的语言,因此这是编译时多态。

  • Virtual methods in OOP: a method of a class can have various implementations tailored to the specifics of its subclasses; each of these is said to override the implementation given in the base class. Given an object that may be of the base class or any of its subclasses, the correct implementation is selected on the fly, thus this is run-time polymorphism.

    OOP中的虚方法:类的方法可以根据其子类的细节定制各种实现;据说这些中的每一个都覆盖了基类中给出的实现。给定一个可能是基类或其任何子类的对象,动态选择正确的实现,因此这是运行时多态。

  • Templates: a feature of some OO languages whereby a function, class, etc. can be parameterised by a type. For example, you can define a generic "list" template class, and then instantiate it as "list of integers", "list of strings", maybe even "list of lists of strings" or the like. Generally, you write the code once for a data structure of arbitrary element type, and the compiler generates versions of it for the various element types.

    模板:某些OO语言的一个特性,其中函数,类等可以通过类型进行参数化。例如,您可以定义一个通用的“列表”模板类,然后将其实例化为“整数列表”,“字符串列表”,甚至可能是“字符串列表列表”等。通常,您为任意元素类型的数据结构编写一次代码,编译器为各种元素类型生成它的版本。

#14


I've provided a high-level overview of polymorphism for another question:

我已经为另一个问题提供了多态性的高级概述:

Polymorphism in c++

c ++中的多态性

Hope it helps. An extract...

希望能帮助到你。提取物......

...it helps to start from a simple test for it and definition of [polymorphism]. Consider the code:

...它有助于从简单的测试开始和[多态性]的定义。考虑一下代码:

Type1 x;
Type2 y;

f(x);
f(y);

Here, f() is to perform some operation and is being given the values x and y as inputs. To be polymorphic, f() must be able to operate with values of at least two distinct types (e.g. int and double), finding and executing type-appropriate code.

这里,f()是执行某些操作,并且给出值x和y作为输入。要具有多态性,f()必须能够使用至少两种不同类型(例如int和double)的值进行操作,查找并执行适合类型的代码。

( continued at Polymorphism in c++ )

(续c ++中的多态)

#15


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.

如果您是音乐作品的倾听者,您可以参考该剧本,例如:巴赫的“Fuga and Tocata”以及所有表演它的音乐家都以自己的方式进行多态化。

This is just an example of a possible design (in Java):

这只是一个可能的设计示例(在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());
}

#16


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:

多态性是程序员根据这些对象的需要编写同名方法的能力,这些方法针对不同类型的对象执行不同的操作。例如,如果您正在开发一个名为Fraction的类和一个名为ComplexNumber的类,则这两个类都可能包含一个名为display()的方法,但每个方法都会以不同方式实现该方法。例如,在PHP中,您可以像这样实现它:

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

其他一些答案似乎暗示多态性仅与继承结合使用;例如,也许Fraction和ComplexNumber都实现了一个名为Number的抽象类,它有一个方法display(),然后Fraction和ComplexNumber都有义务实现。但是你不需要继承来利用多态性。

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:

至少在PHP这样的动态类型语言中(我不了解C ++或Java),多态性允许开发人员在不必提前知道对象类型的情况下调用方法,并相信方法的正确实现将会叫做。例如,假设用户选择创建的数字类型:

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

在这种情况下,即使开发人员无法提前知道用户是选择分数还是复数,也会调用相应的display()方法。

#17


Polymorphism literally means, multiple shapes. (or many form) : Object from different classes and same name method , but workflows are different. A simple example would be:

多态性字面意思是多种形状。 (或多种形式):来自不同类和同名方法的对象,但工作流程不同。一个简单的例子是:

Consider a person X.

考虑一个人X.

He is only one person but he acts as many. You may ask how:

他只是一个人,但他的行为很多。你可能会问:

He is a son to his mother. A friend to his friends. A brother to his sister.

他是他母亲的儿子。朋友给他的朋友。他妹妹的兄弟。

#18


Polymorphism in OOP means a class could have different types, inheritance is one way of implementing polymorphism.

OOP中的多态性意味着一个类可以有不同的类型,继承是实现多态的一种方式。

for example, Shape is an interface, it has Square, Circle, Diamond subtypes. now you have a Square object, you can upcasting Square to Shape automatically, because Square is a Shape. But when you try to downcasting Shape to Square, you must do explicit type casting, because you can't say Shape is Square, it could be Circle as well. so you need manually cast it with code like Square s = (Square)shape, what if the shape is Circle, you will get java.lang.ClassCastException, because Circle is not Square.

例如,Shape是一个界面,它有Square,Circle,Diamond子类型。现在你有了一个Square对象,你可以自动将Square转换为Shape,因为Square是一个Shape。但是当你尝试向下转换Shape到Square时,你必须进行显式类型转换,因为你不能说Shape是Square,它也可以是Circle。所以你需要手动使用Square s =(Square)形状的代码来构建它,如果形状是Circle,你会得到java.lang.ClassCastException,因为Circle不是Square。

#19


Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. In this example that is written in Java, we have three type of vehicle. We create three different object and try to run their wheels method:

多态性是一种物体采取多种形式的能力。当父类引用用于引用子类对象时,OOP中最常见的多态性使用发生。在这个用Java编写的示例中,我们有三种类型的工具。我们创建三个不同的对象并尝试运行他们的*方法:

public class PolymorphismExample {

    public static abstract class Vehicle
    {
        public int wheels(){
            return 0;
        }
    }

    public static class Bike extends Vehicle
    {
        @Override
        public int wheels()
        {
            return 2;
        }
    }

    public static class Car extends Vehicle
    {
        @Override
        public int wheels()
        {
            return 4;
        }
    }

    public static class Truck extends Vehicle
    {
        @Override
        public int wheels()
        {
            return 18;
        }
    }

    public static void main(String[] args)
    {
        Vehicle bike = new Bike();
        Vehicle car = new Car();
        Vehicle truck = new Truck();

        System.out.println("Bike has "+bike.wheels()+" wheels");
        System.out.println("Car has "+car.wheels()+" wheels");
        System.out.println("Truck has "+truck.wheels()+" wheels");
    }

}

The result is:

结果是:

什么是多态,它是什么,以及它是如何使用的?

For more information please visit https://github.com/m-vahidalizadeh/java_advanced/blob/master/src/files/PolymorphismExample.java. I hope it helps.

有关更多信息,请访问https://github.com/m-vahidalizadeh/java_advanced/blob/master/src/files/PolymorphismExample.java。我希望它有所帮助。

#20


In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.

在面向对象的编程中,多态性是指编程语言根据数据类型或类不同地处理对象的能力。更具体地说,它是重新定义派生类的方法的能力。

#21


Polymorphism is the ability to use an object in a given class, where all components that make up the object are inherited by subclasses of the given class. This means that once this object is declared by a class, all subclasses below it (and thier subclasses, and so on until you reach the farthest/lowest subclass) inherit the object and it's components (makeup).

多态性是在给定类中使用对象的能力,其中构成对象的所有组件都由给定类的子类继承。这意味着一旦这个对象被一个类声明,它下面的所有子类(以及它们的子类,依此类推,直到你到达最远/最低的子类)继承对象及其组件(化妆)。

Do remember that each class must be saved in separate files.

请记住,每个类必须保存在单独的文件中。

The following code exemplifies Polymorphism:

以下代码举例说明了多态性:

The SuperClass:

public class Parent {
    //Define things that all classes share
    String maidenName;
    String familyTree;

    //Give the top class a default method
    public void speak(){
         System.out.println("We are all Parents");
    }
}

The father, a subclass:

父亲,一个子类:

public class Father extends Parent{
    //Can use maidenName and familyTree here
    String name="Joe";
    String called="dad";

    //Give the top class a default method
    public void speak(){
        System.out.println("I am "+name+", the father.");
    }
}

The child, another subclass:

孩子,另一个子类:

public class Child extends Father {
    //Can use maidenName, familyTree, called and name here

    //Give the top class a default method
    public void speak(){
        System.out.println("Hi "+called+". What are we going to do today?");
    }
}

The execution method, references Parent class to start:

执行方法,引用Parent类来启动:

public class Parenting{
    public static void main(String[] args) {
        Parent parents = new Parent();
        Parent parent = new Father();
        Parent child = new Child();

        parents.speak();
        parent.speak();
        child.speak();
    }
}

Note that each class needs to be declared in separate *.java files. The code should compile. Also notice that you can continually use maidenName and familyTree farther down. That is the concept of polymorphism. The concept of inheritance is also explored here, where one class is can be used or is further defined by a subclass.

请注意,每个类都需要在单独的* .java文件中声明。代码应该编译。另请注意,您可以继续使用maidenName和familyTree。这就是多态的概念。这里还探讨了继承的概念,其中一个类可以使用或者由子类进一步定义。

Hope this helps and makes it clear. I will post the results when I find a computer that I can use to verify the code. Thanks for the patience!

希望这有助于并明确表达。当我找到一台可以用来验证代码的计算机时,我会发布结果。谢谢你的耐心!

#22


Polymorphism is an ability of object which can be taken in many forms. For example in human class a man can act in many forms when we talk about relationships. EX: A man is a father to his son and he is husband to his wife and he is teacher to his students.

多态性是一种物体的能力,可以采取多种形式。例如,在人类中,当我们谈论关系时,人可以以多种形式行事。 EX:一个男人是他儿子的父亲,他是他妻子的丈夫,他是他的学生的老师。

#23


Polymorphism => Different execution according to instance of class, not type of reference variable.

Polymorphism =>根据类的实例执行不同,而不是引用变量的类型。

A interface type reference variable can refer any of the class instance that implements that interface.

接口类型引用变量可以引用实现该接口的任何类实例。

#24


Polymorphism allows the same routine (function, method) to act on different types.

多态性允许相同的例程(函数,方法)作用于不同类型。

Since many existing answers are conflating subtyping with polymorphism, here are three ways (including subtyping) to implement polymorphism.

由于许多现有的答案都将子类型与多态性混为一谈,因此这里有三种方法(包括子类型)来实现多态性。

  • Parameteric (generic) polymorphism allows a routine to accept one or more type parameters, in addition to normal parameters, and runs itself on those types.
  • 参数(通用)多态性允许例程除了正常参数之外还接受一个或多个类型参数,并在这些类型上运行。

  • Subtype polymorphism allows a routine to act on any subtype of its parameters.
  • 子类型多态性允许例程对其参数的任何子类型起作用。

  • Ad hoc polymorphism generally uses routine overloading to grant polymorphic behavior, but can refer to other polymorphism implementations too.
  • Ad hoc多态通常使用例程重载来授予多态行为,但也可以引用其他多态实现。

See also:

http://wiki.c2.com/?CategoryPolymorphism

https://en.wikipedia.org/wiki/Polymorphism_(computer_science)

#25


In Object Oriented languages, polymorphism allows treatment and handling of different data types through the same interface. For example, consider inheritance in C++: Class B is derived from Class A. A pointer of type A* (pointer to class A) may be used to handle both an object of class A AND an object of class B.

在面向对象语言中,多态性允许通过相同的接口处理和处理不同的数据类型。例如,考虑C ++中的继承:类B是从类A派生的。类型为A *的指针(指向类A的指针)可用于处理类A的对象和类B的对象。

#26


Polymorphism in coding terms is when your object can exist as multiple types through inheritance etc. If you create a class named "Shape" which defines the number of sides your object has then you can then create a new class which inherits it such as "Square". When you subsequently make an instance of "Square" you can then cast it back and forward from "Shape" to "Square" as required.

编码术语中的多态性是指您的对象可以通过继承等存在为多个类型。如果您创建一个名为“Shape”的类来定义对象所具有的边数,那么您可以创建一个继承它的新类,如“Square” ”。当您随后创建“Square”实例时,您可以根据需要将其从“Shape”转发回“Square”。

#27


Polymorphism gives you the ability to create one module calling another, and yet have the compile time dependency point against the flow of control instead of with the flow of control.

多态性使您能够创建一个调用另一个模块的模块,并且具有针对控制流而不是控制流的编译时依赖性点。

By using polymorphism, a high level module does not depend on low-level module. Both depend on abstractions. This helps us to apply the dependency inversion principle(https://en.wikipedia.org/wiki/Dependency_inversion_principle).

通过使用多态,高级模块不依赖于低级模块。两者都取决于抽象。这有助于我们应用依赖性反转原则(https://en.wikipedia.org/wiki/Dependency_inversion_principle)。

This is where I found the above definition. Around 50 minutes into the video the instructor explains the above. https://www.youtube.com/watch?v=TMuno5RZNeE

这是我找到上述定义的地方。大约50分钟后,教练解释了上述内容。 https://www.youtube.com/watch?v=TMuno5RZNeE

#1


If you think about the Greek roots of the term, it should become obvious.

如果你考虑这个术语的希腊词根,它应该变得明显。

  • Poly = many: polygon = many-sided, polystyrene = many styrenes (a), polyglot = many languages, and so on.
  • Poly = many:polygon = many-sided,polystyrene = many styrenes(a),polyglot = many languages,依此类推。

  • Morph = change or form: morphology = study of biological form, Morpheus = the Greek god of dreams able to take any form.
  • 形态=变化或形式:形态=研究生物形态,Morpheus =希腊梦之神能够采取任何形式。

So polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types).

因此,多态性是(在编程中)为不同的底层形式(数据类型)呈现相同的接口的能力。

For example, in many languages, 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.

但是,以同样的方式,像BigDecimal或Rational或Imaginary这样的类也可以提供这些操作,即使它们在不同的数据类型上运行。

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

经典的例子是Shape类和所有可以从它继承的类(方形,圆形,十二面体,不规则多边形,splat等)。

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.

使用多态,这些类中的每一个都将具有不同的底层数据。点形状只需要两个坐标(假设它当然在二维空间中)。圆圈需要一个圆心和半径。正方形或矩形需要两个坐标用于左上角和右下角以及(可能)旋转。不规则多边形需要一系列线条。

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:

通过使类负责其代码及其数据,您可以实现多态。在这个例子中,每个类都有自己的Draw()函数,客户端代码可以简单地执行:

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

这与代码与数据分离的旧方法形成对比,并且您将拥有诸如drawSquare()和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 :-)

面向对象,多态和继承都是密切相关的概念,它们对于了解至关重要。在我漫长的职业生涯中,有很多“银子弹”基本上刚刚失败,但OO范例已经证明是一个很好的。学习它,理解它,喜欢它 - 你会很高兴你做到了:-)


(a) I originally wrote that as a joke but it turned out to be correct and, therefore, not that funny. The momomer styrene happens to be made from carbon and hydrogen, C8H8, and polystyrene is made from groups of that, (C8H8)n.

(a)我最初把它写成一个笑话,但事实证明它是正确的,因此,并不那么有趣。单体苯乙烯恰好由碳和氢制成,C8H8,聚苯乙烯由(C8H8)n的基团制成。

Perhaps I should have stated that a polyp was many occurrences of the letter p although, now that I've had to explain the joke, even that doesn't seem funny either.

也许我应该说息肉是字母p的多次出现,虽然现在我不得不解释这个笑话,即使这看起来也不好笑。

Sometimes, you should just quit while you're behind :-)

有时,你应该在你落后时退出:-)

#2


Polymorphism is when you can treat an object as a generic version of something, but when 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:

这是C#中的一个例子。在控制台应用程序中创建四个类:

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:

现在在控制台应用程序的模块的Main()中创建以下内容:

public void Main()
{
    List<Vehicle> vehicles = new 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.

在这个例子中,我们创建了一个基类Vehicle的列表,它不知道每个子类有多少个*,但是知道每个子类负责知道它有多少个*。

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.

接下来,我们可以循环遍历列表中的每个Vehicle,并对它们进行相同的处理,但是当我们访问每个Vehicle'Wheels'属性时,Vehicle类将该代码的执行委托给相关的子类。

This code is said to be polymorphic, as the exact code which is executed is determined by the sub-class being referenced at runtime.

该代码被称为多态的,因为执行的确切代码由运行时引用的子类确定。

I hope that this helps you.

我希望这对你有所帮助。

#3


From Understanding and Applying Polymorphism in PHP, Thanks Steve Guidetti.

从理解和应用PHP中的多态性,感谢Steve Guidetti。

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.

在编程领域,多态性用于使应用程序更加模块化和可扩展。您可以根据需要创建可互换的对象,而不是描述不同操作过程的混乱条件语句。这是多态性的基本目标。

#4


If anybody says CUT to these people

如果有人对这些人说过CUT

  1. The Surgeon
  2. The Hair Stylist
  3. 发型师

  4. The Actor

What will happen?

会发生什么?

  • The Surgeon would begin to make an incision.
  • 外科医生会开始做切口。

  • The Hair Stylist would begin to cut someone's hair.
  • 发型师会开始剪掉某人的头发。

  • The Actor would abruptly stop acting out of the current scene, awaiting directorial guidance.
  • 演员将突然停止在当前场景中行动,等待导演指导。

So above representation shows What is polymorphism (same name, different behavior) in OOP.

所以上面的表示显示了OOP中的多态(同名,不同行为)是什么。

If you are going for an interview and interviewer asks you tell/show a live example for polymorphism in the same room we are sitting at, say-

如果你要去面试并且面试官要求你告诉/展示我们所在的同一个房间的多态性的实例,比如说 -

Answer - Door / Windows

答案 - 门/窗

Wondering How?

Through Door / Window - a person can come, air can come, light can come, rain can come, etc.

通过门/窗 - 一个人可以来,空气可以来,光可以来,雨可以来,等等。

To understand it better and in a simple manner I used above example.. If you need reference for code follow above answers.

为了更好地理解它,并以简单的方式使用上面的例子..如果你需要参考代码,请按照上面的答案。

#5


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:

例如,假设有一个名为Animal的类,以及一个名为Dog的类,它继承自Animal。多态性是将任何Dog对象视为Animal对象的能力,如下所示:

Dog* dog = new Dog;
Animal* animal = dog;

#6


Polymorphism:

It is the concept of object oriented programming.The ability of different objects to respond, each in its own way, to identical messages is called polymorphism.

它是面向对象编程的概念。不同对象以自己的方式响应相同消息的能力称为多态。

Polymorphism results from the fact that every class lives in its own namespace. The names assigned within a class definition don’t conflict with names assigned anywhere outside it. This is true both of the instance variables in an object’s data structure and of the object’s methods:

多态性源于每个类都在其自己的命名空间中。在类定义中指定的名称与在其外部任何位置分配的名称不冲突。这对象的数据结构和对象方法中的实例变量都是如此:

  • Just as the fields of a C structure are in a protected namespace, so are an object’s instance variables.

    就像C结构的字段在受保护的命名空间中一样,对象的实例变量也是如此。

  • Method names are also protected. Unlike the names of C functions, method names aren’t global symbols. The name of a method in one class can’t conflict with method names in other classes; two very different classes can implement identically named methods.

    方法名称也受到保护。与C函数的名称不同,方法名称不是全局符号。一个类中的方法名称不能与其他类中的方法名称冲突;两个非常不同的类可以实现具有相同名称的方法。

Method names are part of an object’s interface. When a message is sent requesting that an object do something, the message names the method the object should perform. Because different objects can have methods with the same name, the meaning of a message must be understood relative to the particular object that receives the message. The same message sent to two different objects can invoke two distinct methods.

方法名称是对象接口的一部分。当发送消息请求对象执行某些操作时,该消息将命名该对象应执行的方法。因为不同的对象可以具有相同名称的方法,所以必须相对于接收消息的特定对象来理解消息的含义。发送到两个不同对象的相同消息可以调用两个不同的方法。

The main benefit of polymorphism is that it simplifies the programming interface. It permits conventions to be established that can be reused in class after class. Instead of inventing a new name for each new function you add to a program, the same names can be reused. The programming interface can be described as a set of abstract behaviors, quite apart from the classes that implement them.

多态的主要好处是它简化了编程接口。它允许建立可以在课堂上重复使用的约定。您可以重复使用相同的名称,而不是为添加到程序中的每个新函数创建新名称。编程接口可以描述为一组抽象行为,与实现它们的类完全不同。

Examples:

Example-1: Here is a simple example written in Python 2.x.

示例1:这是一个用Python 2.x编写的简单示例。

class Animal:
    def __init__(self, name):    # Constructor of the class
        self.name = name
    def talk(self):              # Abstract method, defined by convention only
        raise NotImplementedError("Subclass must implement abstract method")

class Cat(Animal):
    def talk(self):
        return 'Meow!'

class Dog(Animal):
    def talk(self):
        return 'Woof! Woof!'

animals = [Cat('Missy'),
           Dog('Lassie')]

for animal in animals:
    print animal.name + ': ' + animal.talk()

Example-2: Polymorphism is implemented in Java using method overloading and method overriding concepts.

示例2:使用方法重载和方法覆盖概念在Java中实现多态性。

Let us Consider Car example for discussing the polymorphism. Take any brand like Ford, Honda, Toyota, BMW, Benz etc., Everything is of type Car.

让我们考虑Car讨论多态性的例子。选择福特,本田,丰田,宝马,奔驰等品牌,一切都是汽车类型。

But each have their own advanced features and more advanced technology involved in their move behavior.

但每个都有自己的先进功能和更先进的技术参与其移动行为。

Now let us create a basic type Car

现在让我们创建一个基本类型的汽车

Car.java

public class Car {

    int price;
    String name;
    String color;

    public void move(){
    System.out.println("Basic Car move");
    }

}

Let us implement the Ford Car example.

让我们实施福特汽车的例子。

Ford extends the type Car to inherit all its members(properties and methods).

福特扩展了Car类型以继承其所有成员(属性和方法)。

Ford.java

public class Ford extends Car{
  public void move(){
    System.out.println("Moving with V engine");
  }
}

The above Ford class extends the Car class and also implements the move() method. Even though the move method is already available to Ford through the Inheritance, Ford still has implemented the method in its own way. This is called method overriding.

上面的Ford类扩展了Car类,并且还实现了move()方法。尽管福特通过继承已经可以使用移动方法,但福特仍然以自己的方式实施了该方法。这称为方法覆盖。

Honda.java

public class Honda extends Car{
  public void move(){
    System.out.println("Move with i-VTEC engine");
  }
}

Just like Ford, Honda also extends the Car type and implemented the move method in its own way.

就像福特一样,本田也扩展了Car类型并以自己的方式实现了移动方法。

Method overriding is an important feature to enable the Polymorphism. Using Method overriding, the Sub types can change the way the methods work that are available through the inheritance.

方法覆盖是启用多态性的重要特征。使用方法覆盖,Sub类型可以通过继承更改方法的工作方式。

PolymorphismExample.java

public class PolymorphismExample {
  public static void main(String[] args) {
    Car car = new Car();
    Car f = new Ford();
    Car h = new Honda();

    car.move();
    f.move();
    h.move();

  }
}

Polymorphism Example Output:

多态性示例输出:

In the PolymorphismExample class main method, i have created three objects- Car, Ford and Honda. All the three objects are referred by the Car type.

在PolymorphismExample类主方法中,我创建了三个对象 - 汽车,福特和本田。所有三个对象都由Car类型引用。

Please note an important point here that A super class type can refer to a Sub class type of object but the vice-verse is not possible. The reason is that all the members of the super class are available to the subclass using inheritance and during the compile time, the compiler tries to evaluate if the reference type we are using has the method he is trying to access.

请注意这里的重点是超类类型可以引用Sub类类型的对象,但反之亦然。原因是超类的所有成员都可以使用继承来使用子类,并且在编译期间,编译器会尝试评估我们使用的引用类型是否具有他试图访问的方法。

So, for the references car,f and h in the PolymorphismExample, the move method exists from Car type. So, the compiler passes the compilation process without any issues.

因此,对于PolymorphismExample中的引用car,f和h,移动方法存在于Car类型中。因此,编译器通过编译过程没有任何问题。

But when it comes to the run time execution, the virtual machine invokes the methods on the objects which are sub types. So, the method move() is invoked from their respective implementations.

但是当涉及运行时执行时,虚拟机会调用作为子类型的对象的方法。因此,方法move()从它们各自的实现中调用。

So, all the objects are of type Car, but during the run time, the execution depends on the Object on which the invocation happens. This is called polymorphism.

因此,所有对象都是Car类型,但在运行时,执行依赖于调用发生的Object。这称为多态性。

#7


Simple Explanation by analogy

The President of the United States employs polymorphism. How? Well, he has many advisers:

美国总统采用多态性。怎么样?好吧,他有很多顾问:

  1. Military Advisers
  2. Legal Advisers
  3. Nuclear physicists (as advisers)
  4. 核物理学家(顾问)

  5. Medical advisers
  6. etc etc.

Everyone Should only be responsible for one thing: Example:

每个人都应该对一件事负责:例如:

The president is not an expert in zinc coating, or quantum physics. He doesn't know many things - but he does know only one thing: how to run the country.

总统不是锌涂层或量子物理专家。他不知道很多事情 - 但他只知道一件事:如何管理这个国家。

It's kinda the same with code: concerns and responsibilities should be separated to the relevant classes/people. Otherwise you'd have the president knowing literally everything in the world - the entire Wikipedia. Imagine having the entire wikipedia in a class of your code: it would be a nightmare to maintain.

它与代码有点相同:关注点和责任应该与相关的类/人分开。否则你会让总统知道世界上的一切 - 整个*。想象一下,将整个*放在一个代码类中:维护它将是一场噩梦。

Why is that a bad idea for a president to know all these specific things?

为什么总统要知道所有这些具体的事情是个坏主意?

If the president were to specifically tell people what to do, that would mean that the president needs to know exactly what to do. If the president needs to know specific things himself, that means that when you need to make a change, then you'll need to make it in two places, not just one.

如果总统要专门告诉人们该做什么,那就意味着总统需要知道该做什么。如果总统需要自己了解具体事情,那就意味着当你需要做出改变时,你需要在两个地方做到,而不仅仅是一个。

For example, if the EPA changes pollution laws then when that happens: you'd have to make a change to the EPA Class and also the President class. Changing code in two places rather than one can be dangerous - because it's much harder to maintain.

例如,如果环保署改变了污染法律,那么当发生这种情况时:你必须改变EPA班级和总统班级。在两个地方而不是一个地方更改代码可能很危险 - 因为维护起来要困难得多。

Is there a better approach?

有更好的方法吗?

There is a better approach: the president does not need to know the specifics of anything - he can demand the best advice, from people specifically tasked with doing those things.

有一种更好的方法:总统不需要知道任何事情的具体细节 - 他可以要求那些专门负责这些事情的人提供最好的建议。

He can use a polymorphic approach to running the country.

他可以使用多态方法来运行这个国家。

Example - of using a polymorphic approach:

示例 - 使用多态方法:

All the president does is ask people to advise him - and that's what he actually does in real life - and that's what a good president should do. his advisors all respond differently, but they all know what the president means by: Advise(). He's got hundreds of people streaming into his office. It doesn't actually matter who they are. All the president knows is that when he asks them to "Advise" they know how to respond accordingly:

总统所做的就是要求人们为他提供建议 - 而这正是他在现实生活中所做的事情 - 这就是一位优秀的总统应该做的事情。他的顾问都有不同的反应,但他们都知道总统的意思:建议()。他有数百人涌入他的办公室。实际上他们是谁并不重要。所有总统都知道,当他要求他们“建议”时,他们知道如何做出相应的回应:

public class MisterPresident
{
    public void RunTheCountry()
    {
        // assume the Petraeus and Condi classes etc are instantiated.
        Petraeus.Advise(); // # Petraeus says send 100,000 troops to Fallujah
        Condolezza.Advise(); // # she says negotiate trade deal with Iran
        HealthOfficials.Advise(); // # they say we need to spend $50 billion on ObamaCare
    }
}

This approach allows the president to run the country literally without knowing anything about military stuff, or health care or international diplomacy: the details are left to the experts. The only thing the president needs to know is this: "Advise()".

这种方法允许总统在不知道军事资料,医疗保健或国际外交的情况下从字面上管理国家:详细信息留给专家。总统唯一需要知道的是:“建议()”。

What you DON"T want:

你想要什么:

public class MisterPresident
{
    public void RunTheCountry()
    {
        // people walk into the Presidents office and he tells them what to do
        // depending on who they are.

        // Fallujah Advice - Mr Prez tells his military exactly what to do.
        petraeus.IncreaseTroopNumbers();
        petraeus.ImproveSecurity();
        petraeus.PayContractors();

        // Condi diplomacy advice - Prez tells Condi how to negotiate

        condi.StallNegotiations();
        condi.LowBallFigure();
        condi.FireDemocraticallyElectedIraqiLeaderBecauseIDontLikeHim();

        // Health care

        healthOfficial.IncreasePremiums();
        healthOfficial.AddPreexistingConditions();
    }
}

NO! NO! NO! In the above scenario, the president is doing all the work: he knows about increasing troop numbers and pre-existing conditions. This means that if middle eastern policies change, then the president would have to change his commands, as well as the Petraeus class as well. We should only have to change the Petraeus class, because the President shouldn't have to get bogged down in that sort of detail. He doesn't need to know about the details. All he needs to know is that if he makes one order, everything will be taken care of. All the details should be left to the experts.

没有!没有!没有!在上述情景中,总统正在做所有的工作:他知道增加部队数量和预先存在的条件。这意味着,如果中东政策发生变化,总统将不得不改变他的命令,以及彼得雷乌斯班。我们只需改变彼得雷乌斯班,因为总统不应该陷入这种细节的困境。他不需要知道细节。他需要知道的是,如果他订购了一份订单,那么一切都将得到妥善处理。所有细节都应留给专家。

This allows the president to do what he does best: set general policy, look good and play golf :P.

这使得总统可以做他最擅长的事情:制定一般政策,看起来很好并打高尔夫:P。

How is it actually implemented - through a base class or a common interface

That in effect is polymorphism, in a nutshell. How exactly is it done? Through "implementing a common interface" or by using a base class (inheritance) - see the above answers which detail this more clearly. (In order to more clearly understand this concept you need to know what an interface is, and you will need to understand what inheritance is. Without that, you might struggle.)

简而言之,这实际上是多态性。究竟是怎么做到的?通过“实现通用接口”或使用基类(继承) - 请参阅上面的答案,这些答案更清楚地详述了这一点。 (为了更清楚地理解这个概念,你需要知道接口是什么,你需要了解继承是什么。没有它,你可能会很困难。)

In other words, Petraeus, Condi and HealthOfficials would all be classes which "implement an interface" - let's call it the IAdvisor interface which just contains one method: Advise(). But now we are getting into the specifics.

换句话说,Petraeus,Condi和HealthOfficials都将是“实现接口”的类 - 让我们称之为IAdvisor接口,它只包含一个方法:Advise()。但现在我们正在深入了解细节。

This would be ideal

这将是理想的

    public class MisterPresident
    {
            // You can pass in any advisor: Condi, HealthOfficials, Petraeus etc. The president has no idea who it will be. But he does know that he can ask them to "advise" and that's all Mr Prez cares for.
        public void RunTheCountry(IAdvisor governmentOfficer)
        {             
            governmentOfficer.Advise();              
        }
    }


    public class USA
    {
        MisterPresident president;

        public USA(MisterPresident president)
        {
            this.president = president;
        }

        public void ImplementPolicy()
        {
            IAdvisor governmentOfficer = getAdvisor(); // Returns an advisor: could be condi, or petraus etc.
            president.RunTheCountry(governmentOfficer);
        }
    }

Summary

All that you really need to know is this:

你真正需要知道的是:

  • The president doesn't need to know the specifics - those are left to others.
  • 总统不需要知道具体细节 - 这些细节留给其他人。

  • All the president needs to know is to ask who ever walks in the door to advice him - and we know that they will absolutely know what to do when asked to advise (because they are all in actuality, advisors (or IAdvisors :) )
  • 所有总统需要知道的是询问谁走进门给他建议 - 我们知道他们在被要求提出建议时绝对知道该怎么做(因为他们都是实际的,顾问(或IAdvisors :))

I really hope it helps you. If you don't understand anything post a comment and i'll try again.

我真的希望它对你有所帮助。如果你发表任何评论都不明白,我会再试一次。

#8


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:

通常,这指的是类型A的对象的行为类似于B类对象的能力。在面向对象的编程中,这通常通过继承来实现。一些*链接阅读更多:

EDIT: fixed broken links.

编辑:修复断开的链接。

#9


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

你可以通过一个杯子而不是一个特定的实例。这有助于实现一般性,因为您不必为每种杯子类型提供特定的measure()实例

#10


I know this is an older question with a lot of good answers but I'd like to include a one sentence answer:

我知道这是一个较老的问题,有很多好的答案,但我想包括一句话答案:

Treating a derived type as if it were it's base type.

处理派生类型,就好像它是基类型一样。

There are plenty of examples above that show this in action, but I feel this is a good concise answer.

上面有很多例子说明了这一点,但我觉得这是一个很简洁的答案。

#11


(I was browsing another article on something entirely different.. and polymorphism popped up... Now I thought that I knew what Polymorphism was.... but apparently not in this beautiful way explained.. Wanted to write it down somewhere.. better still will share it... )

(我正在浏览关于完全不同的东西的另一篇文章......并且多态性突然出现......现在我以为我知道多态性是什么......但显然不是以这种美妙的方式解释的......想要把它写在某处......更好还是会分享...)

http://www.eioba.com/a/1htn/how-i-explained-rest-to-my-wife

read on from this part:

请阅读本部分:

..... polymorphism. That's a geeky way of saying that different nouns can have the same verb applied to them.

.....多态性。这是一种令人讨厌的说法,即不同的名词可以使用相同的动词。

#12


The term polymorphism comes from:

术语多态性来自:

poly = many

poly =很多

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

为什么我们使用多态?对于初学者......抽象。在这一点上它应该是足够的信息:)

#13


Generally speaking, it's the ability to interface a number of different types of object using the same or a superficially similar API. There are various forms:

一般来说,它是使用相同或表面上类似的API来连接许多不同类型的对象的能力。有各种形式:

  • Function overloading: defining multiple functions with the same name and different parameter types, such as sqrt(float), sqrt(double) and sqrt(complex). In most languages that allow this, the compiler will automatically select the correct one for the type of argument being passed into it, thus this is compile-time polymorphism.

    函数重载:定义具有相同名称和不同参数类型的多个函数,例如sqrt(float),sqrt(double)和sqrt(complex)。在大多数允许这种情况的语言中,编译器会自动为传递给它的参数类型选择正确的语言,因此这是编译时多态。

  • Virtual methods in OOP: a method of a class can have various implementations tailored to the specifics of its subclasses; each of these is said to override the implementation given in the base class. Given an object that may be of the base class or any of its subclasses, the correct implementation is selected on the fly, thus this is run-time polymorphism.

    OOP中的虚方法:类的方法可以根据其子类的细节定制各种实现;据说这些中的每一个都覆盖了基类中给出的实现。给定一个可能是基类或其任何子类的对象,动态选择正确的实现,因此这是运行时多态。

  • Templates: a feature of some OO languages whereby a function, class, etc. can be parameterised by a type. For example, you can define a generic "list" template class, and then instantiate it as "list of integers", "list of strings", maybe even "list of lists of strings" or the like. Generally, you write the code once for a data structure of arbitrary element type, and the compiler generates versions of it for the various element types.

    模板:某些OO语言的一个特性,其中函数,类等可以通过类型进行参数化。例如,您可以定义一个通用的“列表”模板类,然后将其实例化为“整数列表”,“字符串列表”,甚至可能是“字符串列表列表”等。通常,您为任意元素类型的数据结构编写一次代码,编译器为各种元素类型生成它的版本。

#14


I've provided a high-level overview of polymorphism for another question:

我已经为另一个问题提供了多态性的高级概述:

Polymorphism in c++

c ++中的多态性

Hope it helps. An extract...

希望能帮助到你。提取物......

...it helps to start from a simple test for it and definition of [polymorphism]. Consider the code:

...它有助于从简单的测试开始和[多态性]的定义。考虑一下代码:

Type1 x;
Type2 y;

f(x);
f(y);

Here, f() is to perform some operation and is being given the values x and y as inputs. To be polymorphic, f() must be able to operate with values of at least two distinct types (e.g. int and double), finding and executing type-appropriate code.

这里,f()是执行某些操作,并且给出值x和y作为输入。要具有多态性,f()必须能够使用至少两种不同类型(例如int和double)的值进行操作,查找并执行适合类型的代码。

( continued at Polymorphism in c++ )

(续c ++中的多态)

#15


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.

如果您是音乐作品的倾听者,您可以参考该剧本,例如:巴赫的“Fuga and Tocata”以及所有表演它的音乐家都以自己的方式进行多态化。

This is just an example of a possible design (in Java):

这只是一个可能的设计示例(在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());
}

#16


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:

多态性是程序员根据这些对象的需要编写同名方法的能力,这些方法针对不同类型的对象执行不同的操作。例如,如果您正在开发一个名为Fraction的类和一个名为ComplexNumber的类,则这两个类都可能包含一个名为display()的方法,但每个方法都会以不同方式实现该方法。例如,在PHP中,您可以像这样实现它:

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

其他一些答案似乎暗示多态性仅与继承结合使用;例如,也许Fraction和ComplexNumber都实现了一个名为Number的抽象类,它有一个方法display(),然后Fraction和ComplexNumber都有义务实现。但是你不需要继承来利用多态性。

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:

至少在PHP这样的动态类型语言中(我不了解C ++或Java),多态性允许开发人员在不必提前知道对象类型的情况下调用方法,并相信方法的正确实现将会叫做。例如,假设用户选择创建的数字类型:

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

在这种情况下,即使开发人员无法提前知道用户是选择分数还是复数,也会调用相应的display()方法。

#17


Polymorphism literally means, multiple shapes. (or many form) : Object from different classes and same name method , but workflows are different. A simple example would be:

多态性字面意思是多种形状。 (或多种形式):来自不同类和同名方法的对象,但工作流程不同。一个简单的例子是:

Consider a person X.

考虑一个人X.

He is only one person but he acts as many. You may ask how:

他只是一个人,但他的行为很多。你可能会问:

He is a son to his mother. A friend to his friends. A brother to his sister.

他是他母亲的儿子。朋友给他的朋友。他妹妹的兄弟。

#18


Polymorphism in OOP means a class could have different types, inheritance is one way of implementing polymorphism.

OOP中的多态性意味着一个类可以有不同的类型,继承是实现多态的一种方式。

for example, Shape is an interface, it has Square, Circle, Diamond subtypes. now you have a Square object, you can upcasting Square to Shape automatically, because Square is a Shape. But when you try to downcasting Shape to Square, you must do explicit type casting, because you can't say Shape is Square, it could be Circle as well. so you need manually cast it with code like Square s = (Square)shape, what if the shape is Circle, you will get java.lang.ClassCastException, because Circle is not Square.

例如,Shape是一个界面,它有Square,Circle,Diamond子类型。现在你有了一个Square对象,你可以自动将Square转换为Shape,因为Square是一个Shape。但是当你尝试向下转换Shape到Square时,你必须进行显式类型转换,因为你不能说Shape是Square,它也可以是Circle。所以你需要手动使用Square s =(Square)形状的代码来构建它,如果形状是Circle,你会得到java.lang.ClassCastException,因为Circle不是Square。

#19


Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. In this example that is written in Java, we have three type of vehicle. We create three different object and try to run their wheels method:

多态性是一种物体采取多种形式的能力。当父类引用用于引用子类对象时,OOP中最常见的多态性使用发生。在这个用Java编写的示例中,我们有三种类型的工具。我们创建三个不同的对象并尝试运行他们的*方法:

public class PolymorphismExample {

    public static abstract class Vehicle
    {
        public int wheels(){
            return 0;
        }
    }

    public static class Bike extends Vehicle
    {
        @Override
        public int wheels()
        {
            return 2;
        }
    }

    public static class Car extends Vehicle
    {
        @Override
        public int wheels()
        {
            return 4;
        }
    }

    public static class Truck extends Vehicle
    {
        @Override
        public int wheels()
        {
            return 18;
        }
    }

    public static void main(String[] args)
    {
        Vehicle bike = new Bike();
        Vehicle car = new Car();
        Vehicle truck = new Truck();

        System.out.println("Bike has "+bike.wheels()+" wheels");
        System.out.println("Car has "+car.wheels()+" wheels");
        System.out.println("Truck has "+truck.wheels()+" wheels");
    }

}

The result is:

结果是:

什么是多态,它是什么,以及它是如何使用的?

For more information please visit https://github.com/m-vahidalizadeh/java_advanced/blob/master/src/files/PolymorphismExample.java. I hope it helps.

有关更多信息,请访问https://github.com/m-vahidalizadeh/java_advanced/blob/master/src/files/PolymorphismExample.java。我希望它有所帮助。

#20


In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.

在面向对象的编程中,多态性是指编程语言根据数据类型或类不同地处理对象的能力。更具体地说,它是重新定义派生类的方法的能力。

#21


Polymorphism is the ability to use an object in a given class, where all components that make up the object are inherited by subclasses of the given class. This means that once this object is declared by a class, all subclasses below it (and thier subclasses, and so on until you reach the farthest/lowest subclass) inherit the object and it's components (makeup).

多态性是在给定类中使用对象的能力,其中构成对象的所有组件都由给定类的子类继承。这意味着一旦这个对象被一个类声明,它下面的所有子类(以及它们的子类,依此类推,直到你到达最远/最低的子类)继承对象及其组件(化妆)。

Do remember that each class must be saved in separate files.

请记住,每个类必须保存在单独的文件中。

The following code exemplifies Polymorphism:

以下代码举例说明了多态性:

The SuperClass:

public class Parent {
    //Define things that all classes share
    String maidenName;
    String familyTree;

    //Give the top class a default method
    public void speak(){
         System.out.println("We are all Parents");
    }
}

The father, a subclass:

父亲,一个子类:

public class Father extends Parent{
    //Can use maidenName and familyTree here
    String name="Joe";
    String called="dad";

    //Give the top class a default method
    public void speak(){
        System.out.println("I am "+name+", the father.");
    }
}

The child, another subclass:

孩子,另一个子类:

public class Child extends Father {
    //Can use maidenName, familyTree, called and name here

    //Give the top class a default method
    public void speak(){
        System.out.println("Hi "+called+". What are we going to do today?");
    }
}

The execution method, references Parent class to start:

执行方法,引用Parent类来启动:

public class Parenting{
    public static void main(String[] args) {
        Parent parents = new Parent();
        Parent parent = new Father();
        Parent child = new Child();

        parents.speak();
        parent.speak();
        child.speak();
    }
}

Note that each class needs to be declared in separate *.java files. The code should compile. Also notice that you can continually use maidenName and familyTree farther down. That is the concept of polymorphism. The concept of inheritance is also explored here, where one class is can be used or is further defined by a subclass.

请注意,每个类都需要在单独的* .java文件中声明。代码应该编译。另请注意,您可以继续使用maidenName和familyTree。这就是多态的概念。这里还探讨了继承的概念,其中一个类可以使用或者由子类进一步定义。

Hope this helps and makes it clear. I will post the results when I find a computer that I can use to verify the code. Thanks for the patience!

希望这有助于并明确表达。当我找到一台可以用来验证代码的计算机时,我会发布结果。谢谢你的耐心!

#22


Polymorphism is an ability of object which can be taken in many forms. For example in human class a man can act in many forms when we talk about relationships. EX: A man is a father to his son and he is husband to his wife and he is teacher to his students.

多态性是一种物体的能力,可以采取多种形式。例如,在人类中,当我们谈论关系时,人可以以多种形式行事。 EX:一个男人是他儿子的父亲,他是他妻子的丈夫,他是他的学生的老师。

#23


Polymorphism => Different execution according to instance of class, not type of reference variable.

Polymorphism =>根据类的实例执行不同,而不是引用变量的类型。

A interface type reference variable can refer any of the class instance that implements that interface.

接口类型引用变量可以引用实现该接口的任何类实例。

#24


Polymorphism allows the same routine (function, method) to act on different types.

多态性允许相同的例程(函数,方法)作用于不同类型。

Since many existing answers are conflating subtyping with polymorphism, here are three ways (including subtyping) to implement polymorphism.

由于许多现有的答案都将子类型与多态性混为一谈,因此这里有三种方法(包括子类型)来实现多态性。

  • Parameteric (generic) polymorphism allows a routine to accept one or more type parameters, in addition to normal parameters, and runs itself on those types.
  • 参数(通用)多态性允许例程除了正常参数之外还接受一个或多个类型参数,并在这些类型上运行。

  • Subtype polymorphism allows a routine to act on any subtype of its parameters.
  • 子类型多态性允许例程对其参数的任何子类型起作用。

  • Ad hoc polymorphism generally uses routine overloading to grant polymorphic behavior, but can refer to other polymorphism implementations too.
  • Ad hoc多态通常使用例程重载来授予多态行为,但也可以引用其他多态实现。

See also:

http://wiki.c2.com/?CategoryPolymorphism

https://en.wikipedia.org/wiki/Polymorphism_(computer_science)

#25


In Object Oriented languages, polymorphism allows treatment and handling of different data types through the same interface. For example, consider inheritance in C++: Class B is derived from Class A. A pointer of type A* (pointer to class A) may be used to handle both an object of class A AND an object of class B.

在面向对象语言中,多态性允许通过相同的接口处理和处理不同的数据类型。例如,考虑C ++中的继承:类B是从类A派生的。类型为A *的指针(指向类A的指针)可用于处理类A的对象和类B的对象。

#26


Polymorphism in coding terms is when your object can exist as multiple types through inheritance etc. If you create a class named "Shape" which defines the number of sides your object has then you can then create a new class which inherits it such as "Square". When you subsequently make an instance of "Square" you can then cast it back and forward from "Shape" to "Square" as required.

编码术语中的多态性是指您的对象可以通过继承等存在为多个类型。如果您创建一个名为“Shape”的类来定义对象所具有的边数,那么您可以创建一个继承它的新类,如“Square” ”。当您随后创建“Square”实例时,您可以根据需要将其从“Shape”转发回“Square”。

#27


Polymorphism gives you the ability to create one module calling another, and yet have the compile time dependency point against the flow of control instead of with the flow of control.

多态性使您能够创建一个调用另一个模块的模块,并且具有针对控制流而不是控制流的编译时依赖性点。

By using polymorphism, a high level module does not depend on low-level module. Both depend on abstractions. This helps us to apply the dependency inversion principle(https://en.wikipedia.org/wiki/Dependency_inversion_principle).

通过使用多态,高级模块不依赖于低级模块。两者都取决于抽象。这有助于我们应用依赖性反转原则(https://en.wikipedia.org/wiki/Dependency_inversion_principle)。

This is where I found the above definition. Around 50 minutes into the video the instructor explains the above. https://www.youtube.com/watch?v=TMuno5RZNeE

这是我找到上述定义的地方。大约50分钟后,教练解释了上述内容。 https://www.youtube.com/watch?v=TMuno5RZNeE