什么是多态,简单解释一下?

What is polymorphism, explained simply?

我知道这是一个重复的问题,而且有点 "soft" 但我不喜欢那里的任何其他解释,并且希望听到一个简单的回答,不会泛化到令人困惑的地步.

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

多态性只是"being able to perform functions (or is it methods?) of an interface, such as adding, subtracting, etc, on objects of different data types such as integers, floats, etc"吗?

基本上是运算符重载吗?还是模板化?

一般来说,能力以多种形式出现。在面向对象编程中,多态性是指编程语言根据对象的数据类型或 class 以不同方式处理对象的能力。更具体地说,它是为派生的 classes 重新定义方法的能力。例如,给定一个基础 class 形状,多态性使程序员能够为任意数量的派生 class 定义不同的区域方法,例如圆形、矩形和三角形。无论物体是什么形状,对其应用面积法都会return得到正确的结果。多态性被认为是任何真正的面向对象编程语言 (OOPL) 的要求。

简单的方法重载和方法覆盖...

一个最小但易于理解的Java示例:

public class Animal {
    public void eat() {
        System.out.println("wow!");
    }
}

public class Horse extends Animal {
    public void eat() {
        System.out.println("iiiihhh!");
    }
}

public class Dog extends Animal {
    public void eat() {
        System.out.println("whoa!");
    }
}

通过覆盖它们的父 类 方法,DogHorse 类 都可以修改它们的 eat() 方法,而您可以更通用地使用它们通过调用超类 Animal.

的转换
Animal animal = new Animal();
Animal dog = new Dog();
Animal horse = new Horse();

animal.eat();  // prints "wow!"
dog.eat();     // prints "whoa!"
horse.eat();   // prints "iiiihhh!"

正如三客所说,简单来说就是方法重载和方法重写

多态性 只是一个花哨的词,这意味着您可以使用更通用的术语来指代特定类型的对象。

它与接口

齐头并进

界面:同一个词,几种口味

您可以直接说 "I got a new car" 而不是 "I got a new Vauxhall Corsa"。如果你刚买了一辆福特嘉年华,这句话也是正确的,因为那也是一辆汽车。英文单词 'car' 的灵​​活性(多态性)意味着您不必确切指定它是哪种汽车。你的听众会知道你的前驱动器上有一个现代装置,它设计用于发出哔哔声、转向和在路上行驶,即使沃克斯豪尔和福特发动机的确切机制可能彼此不同。

多态性采用此接口,让您将福特嘉年华简单地称为汽车:

Car car = new Ford();

来自this blog:

Polymorphism means using a superclass variable to refer to a subclass object. For example, consider this simple inheritance hierarchy and code:

abstract class Animal {
    abstract void talk();
}
class Dog extends Animal {
    void talk() {
        System.out.println("Woof!");
    }
}
class Cat extends Animal {
    void talk() {
        System.out.println("Meow.");
    }
}

Polymorphism allows you to hold a reference to a Dog object in a variable of type Animal, as in:

Animal animal = new Dog();

PS鉴于其他答案,您可能还想知道the difference between an abstract class and an interface