在Java中,您可以将子类的对象存储为超类类型,为什么要这样做?



当您可以使用子类时,为什么要将"thing"对象声明为超类,这将使您能够访问所有相同的方法和字段,并且不需要对B类中的方法进行类型转换。

public class A{}
public class B extends A{}
public class main()
{
  A thing = new B();
}

这称为多态性。如果您有另一个名为 C extends A 的类,则可以创建一个List<A>并将BC放在那里。然后你可以迭代它们并调用通用方法等。

也许是因为您想同时feed()几个Animal,而不关心Animal的真实类型:

interface Animal { void feed();}
class Dog implements Animal { public void feed() { /* feed a dog (give it a cat) */ }}
class Cat implements Animal { public void feed() { /* feed a cat (give it a bird) */ }}
class Cow implements Animal { public void feed() { /* feed a cow (give it some grass) */ }}
// Now I have some animals mixed somewhere (note that I am allowed to have the array declaring a supertype (Animal), and it can contain many kind of different animals)
Animal[] manyAnimals = new Animal[]{ new Dog(), new Cat(), new Cow() };
// I can feed them all without knowing really what kind of Animal they are. I just know they are all Animal, and they will all provide a feed() method.
for(Animal some : manyAnimals) { some.feed(); }

它是多态性。

此示例可能会帮助您理解它。

在一家公司中,既有正式员工,也有合同员工。对于不同类型的员工,工资计算方式不同。但PF计算对于这两种类型的员工都是通用的。因此,在这种情况下,您可以在超类(员工(中编写通用代码,而只能在子类(永久员工和合同员工(中编写自定义代码。通过这种方式,您可以使代码可重用,而不是一次又一次地编写,还可以实现动态多态性。大多数情况下,员工类型是在运行时决定的。

最新更新