什么是多态性,它的用途是什么,如何使用它?
当前回答
我知道这是一个有很多好答案的老问题,但我想用一句话来回答:
将派生类型视为其基类型。
上面有很多例子可以说明这一点,但我觉得这是一个很好的简明答案。
其他回答
通常这指的是A类型对象的行为与b类型对象相似的能力。在面向对象编程中,这通常是通过继承来实现的。一些维基百科的链接来阅读更多:
面向对象编程中的多态性 类型多态性
编辑:固定破碎的链接。
多态:
根据类的实例而不是引用变量的类型执行不同的执行。
接口类型引用变量可以引用实现该接口的任何类实例。
多态是指您可以将对象视为某个对象的通用版本,但当您访问它时,代码将确定它的确切类型并调用相关代码。
下面是一个c#的例子。在控制台应用程序中创建四个类:
public abstract class Vehicle
{
public abstract int Wheels;
}
public class Bicycle : Vehicle
{
public override int Wheels()
{
return 2;
}
}
public class Car : Vehicle
{
public override int Wheels()
{
return 4;
}
}
public class Truck : Vehicle
{
public override int Wheels()
{
return 18;
}
}
现在在控制台应用程序模块的Main()中创建以下内容:
public void Main()
{
List<Vehicle> vehicles = new List<Vehicle>();
vehicles.Add(new Bicycle());
vehicles.Add(new Car());
vehicles.Add(new Truck());
foreach (Vehicle v in vehicles)
{
Console.WriteLine(
string.Format("A {0} has {1} wheels.",
v.GetType().Name, v.Wheels));
}
}
在这个例子中,我们创建了一个基类Vehicle的列表,它不知道它的每个子类有多少个轮子,但是知道每个子类负责知道它有多少个轮子。
然后我们将自行车、汽车和卡车添加到列表中。
接下来,我们可以循环遍历列表中的每个Vehicle,并将它们都视为相同的,但是当我们访问每个Vehicles 'Wheels'属性时,Vehicle类将该代码的执行委托给相关的子类。
该代码被称为多态代码,因为执行的确切代码是由在运行时引用的子类决定的。
我希望这对你有所帮助。
在编码术语中,多态性是指您的对象可以通过继承等方式以多种类型存在。如果你创建了一个名为“Shape”的类,它定义了对象的边数,那么你可以创建一个继承它的新类,如“Square”。当你随后创建一个“Square”实例时,你可以根据需要将它从“Shape”前后转换为“Square”。
多态性是在给定类中使用对象的能力,其中组成对象的所有组件都由给定类的子类继承。这意味着一旦这个对象被一个类声明,它下面的所有子类(以及它们的子类,直到你到达最远/最低的子类)继承对象和它的组件(化妆)。
请记住,每个类必须保存在单独的文件中。
下面的代码演示了多态性:
超类:
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.");
}
}
child,另一个子类:
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();
}
}
注意,每个类需要在单独的*.java文件中声明。 代码应该被编译。 还要注意,您可以继续使用maidenName和familyTree。 这就是多态性的概念。 这里还探讨了继承的概念,可以使用一个类,或者由子类进一步定义。
希望这能帮到你,让你明白。 当我找到一台我可以用来验证代码的计算机时,我会发布结果。谢谢您的耐心等待!