gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:28:15 24 4
gpt4 key购买 nike

关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

7年前关闭。




Improve this question




我知道这是一个重复的问题,而且有点“软”,但我不喜欢那里的任何其他解释,并希望听到一个简单的回答,它不会泛化到令人困惑的程度。

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

多态性是否只是“能够对不同数据类型(如整数、浮点数等)的对象执行接口(interface)的功能(或者是方法?),例如加法、减法等”?

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

最佳答案

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

它与 齐头并进接口(interface)

接口(interface):同一个字,几种口味

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

多态性采用这个接口(interface),让您将您的福特嘉年华简单地称为汽车:

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 .

关于definition - 什么是多态,简单解释一下?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29853182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com