Animal 是基类。如果您扩展 Animal,您可以在该类中添加额外的方法和实例变量,您实际上做得正确。
一旦您实例化了一个子类(扩展基类的类,例如:new Cat())但将其分配给基类的类型(Animal),您就只能调用那里可用的方法,即在您的情况下,您只能调用在 Animal 类中声明的方法。
假设你有一个班级Animal:
public class Animal {
public void makeSound() {
System.out.println("Default sound");
}
}
现在您创建一个扩展 Animal 的类 Cat:
public class Cat extends Animal {
private int catProperty = 5;
//Override method of base class
public void makeSound() {
System.out.println("Meow");
}
public int getCatProperty(){
return this.catProperty;
}
}
另一个名为Dog 的类扩展了Animal:
public class Dog extends Animal {
private int dogProperty = 8;
//Override method of base class
public void makeSound() {
System.out.println("Woof");
}
public int getDogProperty(){
return this.dogProperty;
}
}
由于Animal 是基类,您现在可以创建一个包含Cats 和Dogs 的array of type Animal。
Animal[] animals = new Animal[2];
animals[0] = new Cat();
animals[1] = new Dog();
for (Animal animal : animals) {
animal.makeSound();
}
每个animals(Cat 和Dog)现在都将打印正确的声音。
如果您确实需要调用子类特定方法,则必须将对象转换回该子类的实例。在这种情况下,您必须确定子类是什么类型。
例如:
for (Animal animal : animals) {
// Calls overriden method
animal.makeSound();
// This is illegal. Method getCatProperty is not declared in Animal
animal.getCatProperty();
// This is illegal. Method getDogProperty is not declared in Animal class
animal.getDogProperty();
/*
* IF YOU HAVE TO CALL CHILD CLASS SPECIFIC METHODS, DO IT LIKE THIS:
*/
// Checks if animal is of type Cat
if (animal instanceof Cat) {
// Casts animal to instance of Cat
Cat cat = (Cat) animal;
// Calls specific Cat instance method
System.out.println(cat.getCatProperty());
}
// Checks if animal is of type Dog
if (animal instanceof Dog) {
// Casts animal to instance of Dog
Dog dog = (Dog) animal;
// Calls specific Dog instance method
System.out.println(dog.getDogProperty());
}
}
顺便说一句:如果您不打算直接创建 Animal (Animal a = new Animal()) 的实例,则应将类本身和应被子类覆盖的方法声明为 abstract。
public abstract class Animal {
public abstract void makeSound();
}
另外,如果基类只有子类可用的方法而没有实例变量,最好使用接口而不是 (abstract) 类。
public interface Animal {
public abstract void makeSound();
}
那么具体类的接口必须是implemented(而不是extended)。
public class Cat implements Animal {
public void makeSound() {
System.out.println("Meow");
}
}
希望这会有所帮助!