这个实际不叫铸造这是一个多态性的例子。它允许变量根据与其他类的继承关系采用不同的类型。
例如,假设您正在编写程序来模拟动物园。你将有一个名为Zoo
的班级和一个名为Animal
的班级。还有几个类别从Animal
类延伸:Lion
,Zebra
和Elephant
。
这将是非常有用的,以保持所有这些对象在一个列表中组合在一起的,但因为它们是不同类型的,即:Lion
,Zebra
和Elephant
,你不能把它们存储在一个单独的列表,你将不得不保持一个单独的名单每个类型的动物。这是多态性发挥作用的地方。
由于每个班Lion
,Zebra
,并Elephant
全部来自Animal
类,我们可以简单地将它们存储在Animal
类型的列表扩展。
代码示例:
public class Zoo
{
private List<Animal> animals;
public Zoo()
{
this.animals = new ArrayList<>();
}
//notice this method takes an Animal object as a parameter
public void add(Animal a)
{
this.animals.add(a);
}
}
public abstract class Animal
{
private String name;
private String type;
public Animal(String name, String type)
{
this.name = name;
this.type = type;
}
//all subclasses must implement this method
public abstract void speak();
}
public class Lion extends Animal
{
private String animalType = "Lion";
public Lion(String name)
{
super(name, animalType);
}
public void speak()
{
System.out.println("ROAR");
}
}
//....etc for the other two animals
public class TestZoo
{
public static void main(String[] args)
{
Zoo myZoo = new Zoo();
Lion l = new Lion("Larry");
Elephant e = new Elephant("Eli");
Zebra z = new Zebra("Zayne");
myZoo.add(l); //<-- note that here I don't pass Animal objects to the
myZoo.add(e); // add method but subclasses of Animal
myZoo.add(z);
}
}
希望这有助于,即使有一个愚蠢的例子。
好吧,这是有道理的,但在主要方法,如果我反而写 '动物l =新狮子(“拉里”); 动物e =新象(“Eli”); 动物z =新斑马(“Zayne”);' 什么新功能会给? – 2012-04-13 03:48:07
@Hubrid它提供的功能是可以将所有对象存储在同一个列表或容器中,即使它们都具有不同的类型。 – 2012-04-13 03:49:41
我知道这是一种创建动物物体的有效方法,我只是为什么'动物l =新狮子(“拉里”);'永远是首选/不是首选的狮子l =新狮子(“拉里“);'。 – 2012-04-13 03:50:53