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

前端 未结 28 2695
南笙
南笙 2020-11-21 07:08

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

相关标签:
28条回答
  • 2020-11-21 07:54

    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.

    0 讨论(0)
  • 2020-11-21 07:55

    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:

    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.

    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!

    0 讨论(0)
  • 2020-11-21 07:56

    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.

    0 讨论(0)
  • 2020-11-21 07:56

    What is polymorphism?

    Polymorphism is the ability to:

    • Invoke an operation on an instance of a specialized type by only knowing its generalized type while calling the method of the specialized type and not that of the generalized type: it is dynamic polymorphism.

    • Define several methods having the save name but having differents parameters: it is static polymorphism.

    The first if the historical definition and the most important.

    What is polymorphism used for?

    It allows to create strongly-typed consistency of the class hierarchy and to do some magical things like managing lists of objects of differents types without knowing their types but only one of their parent type, as well as data bindings.

    Strong and weak typing

    Sample

    Here are some Shapes like Point, Line, Rectangle and Circle having the operation Draw() taking either nothing or either a parameter to set a timeout to erase it.

    public class Shape
    {
     public virtual void Draw()
     {
       DoNothing();
     }
     public virtual void Draw(int timeout)
     {
       DoNothing();
     }
    }
    
    public class Point : Shape
    {
     int X, Y;
     public override void Draw()
     {
       DrawThePoint();
     }
    }
    
    public class Line : Point
    {
     int Xend, Yend;
     public override Draw()
     {
       DrawTheLine();
     }
    }
    
    public class Rectangle : Line
    {
     public override Draw()
     {
       DrawTheRectangle();
     }
    }
    
    var shapes = new List<Shape> { new Point(0,0), new Line(0,0,10,10), new rectangle(50,50,100,100) };
    
    foreach ( var shape in shapes )
      shape.Draw();
    

    Here the Shape class and the Shape.Draw() methods should be marked as abstract.

    They are not for to make understand.

    Explaination

    Without polymorphism, using abstract-virtual-override, while parsing the shapes, it is only the Spahe.Draw() method that is called as the CLR don't know what method to call. So it call the method of the type we act on, and here the type is Shape because of the list declaration. So the code do nothing at all.

    With polymorphism, the CLR is able to infer the real type of the object we act on using what is called a virtual table. So it call the good method, and here calling Shape.Draw() if Shape is Point calls the Point.Draw(). So the code draws the shapes.

    More readings

    C# - Polymorphism (Level 1)

    Polymorphism in Java (Level 2)

    Polymorphism (C# Programming Guide)

    Virtual method table

    0 讨论(0)
  • 2020-11-21 07:57

    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.

    See also:

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

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

    0 讨论(0)
  • 2020-11-21 07:58

    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:

    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.

    0 讨论(0)
提交回复
热议问题