“new”关键字使您的机器为新对象分配内存。
在这种情况下,您正在初始化的新对象是一个数组,并且该数组有足够的空间来容纳 4 个动物对象。由于 Cat 扩展了动物,因此猫也可以在这里,但任何其他动物都可以是 Dogs、Pigs,只要它们扩展了 Animal。
由于这是一个动物类型的数组,即使其中有猫对象,您也只能引用动物类型的方法声明。
在我们转到一个有数组的例子之前,这里是一个没有数组的例子:
public static void main(String[] args) {
Animal myCat = new Cat();
// prints "meow". Works because it's from an animal method
myCat.speak();
// This doesn't work - unknown method - b/c it's not declared in animal class
myCat.lickSelf();
}
private static class Animal {
public void speak() {
System.out.println("barf");
}
}
private static class Cat extends Animal {
public void speak(){
System.out.println("meow");
}
public void lickSelf(){
System.out.println("slurp");
}
}
现在让我们来看看数组的东西:
任何扩展 cat 的对象都可以放在这里,但您只能访问 Animal 属性。
public static void main(String[] args) {
Animal[] myCats = new Cat[4];
myCats[0] = new Cat(); // can only put cats in here
myCats[1] = new Cat(); // but can only reference Animal properties
myCats[2] = new Cat();
myCats[3] = new Animal(); // Throws exception, must be a cat.
myCats[1].speak(); // prints "meow"
// This doesn't work, even though a cat object is here.
//Can only reference as an Animal.
myCats[2].lickSelf();
}
如果你想使用 cat 方法/属性,你需要这样做:
Cat[] myCats = new Cat[4]
如果您只想使用可能被覆盖的动物属性,但此处只允许猫,请使用:
Animal[] myCats = new Cat[4]
如果您只想使用动物属性,但允许任何类型的动物:
Animal[] myCats = new Animal[4]