What is polymorphism, what is it for, and how is i

2018-12-31 03:34发布

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

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

27条回答
梦醉为红颜
2楼-- · 2018-12-31 03:44

Polymorphism is the ability of the programmer to write methods of the same name that do different things for different types of objects, depending on the needs of those objects. For example, if you were developing a class called Fraction and a class called ComplexNumber, both of these might include a method called display(), but each of them would implement that method differently. In PHP, for example, you might implement it like this:

//  Class definitions

class Fraction
{
    public $numerator;
    public $denominator;

    public function __construct($n, $d)
    {
        //  In real life, you'd do some type checking, making sure $d != 0, etc.
        $this->numerator = $n;
        $this->denominator = $d;
    }

    public function display()
    {
        echo $this->numerator . '/' . $this->denominator;
    }
}

class ComplexNumber
{
    public $real;
    public $imaginary;

    public function __construct($a, $b)
    {
        $this->real = $a;
        $this->imaginary = $b;
    }

    public function display()
    {
        echo $this->real . '+' . $this->imaginary . 'i';
    }
}


//  Main program

$fraction = new Fraction(1, 2);
$complex = new ComplexNumber(1, 2);

echo 'This is a fraction: '
$fraction->display();
echo "\n";

echo 'This is a complex number: '
$complex->display();
echo "\n";

Outputs:

This is a fraction: 1/2
This is a complex number: 1 + 2i

Some of the other answers seem to imply that polymorphism is used only in conjunction with inheritance; for example, maybe Fraction and ComplexNumber both implement an abstract class called Number that has a method display(), which Fraction and ComplexNumber are then both obligated to implement. But you don't need inheritance to take advantage of polymorphism.

At least in dynamically-typed languages like PHP (I don't know about C++ or Java), polymorphism allows the developer to call a method without necessarily knowing the type of object ahead of time, and trusting that the correct implementation of the method will be called. For example, say the user chooses the type of Number created:

$userNumberChoice = $_GET['userNumberChoice'];

switch ($userNumberChoice) {
    case 'fraction':
        $userNumber = new Fraction(1, 2);
        break;
    case 'complex':
        $userNumber = new ComplexNumber(1, 2);
        break;
}

echo "The user's number is: ";
$userNumber->display();
echo "\n";

In this case, the appropriate display() method will be called, even though the developer can't know ahead of time whether the user will choose a fraction or a complex number.

查看更多
牵手、夕阳
3楼-- · 2018-12-31 03:45

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.

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

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.

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.

Let us Consider Car example for discussing the polymorphism. Take any brand like Ford, Honda, Toyota, BMW, Benz etc., Everything is of type 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).

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.

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.

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.

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.

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.

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.

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.

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.

查看更多
人间绝色
4楼-- · 2018-12-31 03:46

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. Medical advisers
  5. 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.

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.

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.

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

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

查看更多
看淡一切
5楼-- · 2018-12-31 03:47

If anybody says CUT to these people

  1. The Surgeon
  2. The Hair Stylist
  3. 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.

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.

查看更多
浅入江南
6楼-- · 2018-12-31 03:47

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

查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 03:48

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

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

( continued at Polymorphism in c++ )

查看更多
登录 后发表回答