Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oop 多态性是什么,它的用途是什么,它是如何使用的?_Oop_Polymorphism_Computer Science - Fatal编程技术网

Oop 多态性是什么,它的用途是什么,它是如何使用的?

Oop 多态性是什么,它的用途是什么,它是如何使用的?,oop,polymorphism,computer-science,Oop,Polymorphism,Computer Science,什么是多态性,它的用途是什么,它是如何使用的?通常指类型A的对象能够像类型B的对象一样工作。在面向对象编程中,这通常是通过继承实现的。一些维基百科链接可阅读更多内容: 编辑:修复断开的链接。多态性是将对象类视为父类的能力 例如,假设有一个名为Animal的类和一个名为Dog的类继承自Animal。多态性是指将任何狗类对象视为动物对象的能力,如下所示: Dog* dog = new Dog; Animal* animal = dog; 让我们打个比方。对于一个给定的音乐剧本,每一个演奏它

什么是多态性,它的用途是什么,它是如何使用的?

通常指类型A的对象能够像类型B的对象一样工作。在面向对象编程中,这通常是通过继承实现的。一些维基百科链接可阅读更多内容:


编辑:修复断开的链接。

多态性是将对象类视为父类的能力

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

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

让我们打个比方。对于一个给定的音乐剧本,每一个演奏它的音乐家在诠释中都有自己的风格

音乐家可以用接口进行抽象,音乐家所属的类型可以是一个abstrac类,它定义了一些解释的全局规则,每个演奏的音乐家都可以用一个具体的类进行建模

如果你是音乐作品的听众,你可以参考剧本,例如巴赫的《富加与托卡塔》,每一位演奏这部作品的音乐家都会以自己的方式演奏

这只是一个可能的设计示例(Java):


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

如果您考虑该术语的希腊词根,它应该变得显而易见

  • Poly=many:polygon=multi-sided,聚苯乙烯=many-styrenes(a),polyglot=many-language,依此类推
  • 形态=变化或形态:形态=生物形态的研究,形态=希腊梦之神,能够以任何形式出现
因此,多态性是(在编程中)为不同的底层形式(数据类型)提供相同接口的能力

例如,在许多语言中,整数和浮点都是隐式多态的,因为您可以进行加法、减法、乘法等操作,而不考虑类型的不同。在通常的术语中,它们很少被视为对象

但是,以同样的方式,像
BigDecimal
Rational
invential
这样的类也可以提供这些操作,即使它们对不同的数据类型进行操作

经典的例子是
Shape
类以及可以从中继承的所有类(正方形、圆形、十二面体、不规则多边形、splat等)

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

通过使类负责其代码和数据,可以实现多态性。在本例中,每个类都有自己的
Draw()
函数,客户端代码只需执行以下操作:

shape.Draw()
以获得任何形状的正确行为

这与旧的处理方式不同,在旧的处理方式中,代码与数据是分开的,您可以使用诸如
drawSquare()
drawCircle()
之类的函数

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


(a) 我最初写这篇文章是作为一个笑话,但后来证明它是正确的,因此,没有那么好笑。单体苯乙烯恰好由碳和氢组成,
C8H8
,而聚苯乙烯则由碳和氢组成,
(C8H8)n

也许我应该说息肉是字母
p
的多次出现,尽管现在我不得不解释这个笑话,即使这样也不好笑


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

多态性这个术语来自:

多边形=多个

形态=改变的能力

在编程中,多态性是一种“技术”,它允许您将对象视为不止一种类型的事物。例如:

student对象也是person对象。如果你“看”(即演员)学生,你可能会要求学生证。你不能总是对一个人这样做,对吗?(一个人不一定是学生,因此可能没有学生ID)。然而,一个人可能有一个名字。学生也是

总之,从不同的“角度”看同一个物体可以给你不同的“视角”(即不同的属性或方法)

因此,这种技术可以让你构建可以从不同角度“观察”的东西


我们为什么使用多态性?首先。。。抽象。现在应该足够了:)

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

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

  • OOP中的虚拟方法:一个类的方法可以根据其子类的具体情况定制各种实现;据说,每一个都覆盖了基类中给出的实现
    shape.Draw()
    
    //  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";
    
    This is a fraction: 1/2
    This is a complex number: 1 + 2i
    
    $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";
    
    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
    }
    
    Type1 x;
    Type2 y;
    
    f(x);
    f(y);
    
    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()
    
    public class Car {
    
        int price;
        String name;
        String color;
    
        public void move(){
        System.out.println("Basic Car move");
        }
    
    }
    
    public class Ford extends Car{
      public void move(){
        System.out.println("Moving with V engine");
      }
    }
    
    public class Honda extends Car{
      public void move(){
        System.out.println("Move with i-VTEC engine");
      }
    }
    
    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();
    
      }
    }
    
    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");
        }
    }
    
    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.");
        }
    }
    
    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?");
        }
    }
    
    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();
        }
    }
    
    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");
        }
    
    }
    
    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
        }
    }
    
    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();
        }
    }
    
        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);
            }
        }
    
    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();