动物cat = new Cat()
您创建了 Cat 实例的编译器“忘记了”。
您的源代码中说:我有一个名为cat
的变量,它是Animal
的实例。
“动物”类上没有方法meow()
。
如果要调用子类方法,则需要一个子类实例:
Cat cat = new Cat();
cat.meow();
,或者您需要播放。基本上,您告诉编译器:“我比您更了解”。
Animal cat = new Cat();
( (Cat) cat).meow();
重点是:java是静态类型的。在python中,解释器将仅查看该cat
是否有一个可以调用的名为meow()
的方法。在Java中无法正常工作。
,
Animal
是基类。如果您扩展Animal
,则可以在该类中添加其他方法和实例变量,而实际上它们是正确完成的。
实例化一个子类(扩展了基类的类,例如:new Cat()
)但将其分配给基类的类型(Animal
)后,您只能调用方法在那里可用,即您只能调用Animal
类中声明的方法。
假设您拥有Animal
类:
public class Animal {
public void makeSound() {
System.out.println("Default sound");
}
}
现在,您创建一个扩展Cat
的类Animal
:
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
是基类,因此您现在可以创建包含array of type Animal
和Cats
的{{1}}。
Dogs
每个Animal[] animals = new Animal[2];
animals[0] = new Cat();
animals[1] = new Dog();
for (Animal animal : animals) {
animal.makeSound();
}
(animals
和Cat
)现在都将打印正确的声音。
如果确实需要调用特定于子类的方法,则必须将对象投射回该子类的实例。在这种情况下,您必须确定子类的类型。
例如:
Dog
仅作为旁注:如果您不打算直接创建Animal(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 a = new Animal()
。 / p>
abstract
此外,如果基类仅具有方法,而子类不应该使用实例变量,则最好使用接口而不是(public abstract class Animal {
public abstract void makeSound();
}
)类。
abstract
接口必须由具体类为public interface Animal {
public abstract void makeSound();
}
(而不是implemented
)。
extended
希望这会有所帮助!
本文链接:https://www.f2er.com/3125787.html