gpt4 book ai didi

java - 父类(super class)引用不应该能够调用其子类独有的方法,但是

转载 作者:行者123 更新时间:2023-12-01 11:51:24 24 4
gpt4 key购买 nike

但是,如果父类(super class)有一个抽象方法,并且该方法在其具体的子类中实现,我们仍然可以使用父类(super class)的对象来调用该方法的子类实现。

怎么会这样?

与重载方法相同,即使您使用父类(super class)的引用调用子类的实现,也会调用它。

让我更具体地说...

假设 Animal 是父类(super class),Dog 是子类。现在,我这样做:

Animal a = new Dog();

这意味着 a 是对动物类的引用,对吧?

现在,如果我这样做,a.function(); (假设该函数在 Animal 中定义并在 Dog 中重写),Animal 的版本应该被调用,因为 a 是对动物的引用,但事实恰恰相反。

最佳答案

这意味着父类(super class)无法调用子类中定义的方法,因为父类(super class)不知道它们。对于抽象方法,父类(super class)知道它们,因此可以调用它们。非抽象和非 final方法也会发生这种情况:子类可以修改它们,而不会注意到父类(super class),并且父类(super class)仍然可以正常工作。

您所描述的是编译时和执行时(也称为运行时)之间的差异。在编译时,变量只能调用在声明变量的类型上定义的方法,例如Animal Animalanimal 变量只能调用 Animal 类中定义的方法。在执行时,方法的执行将由属于对象引用实例的类处理,例如Animal Animal = new Dog(); 那么 animal 行为将由 Dog 类中声明的行为定义。

示例:

public class Animal {
abstract void breath();
}

public class Dog extends Animal {
@Override
public void breath() {
System.out.println("Dog breathing");
}

public void bark() {
System.out.println("woof!");
}
}

public class Client {
public static void main(String[] args) {
//animal variable is of type Animal
//and initialized as a Dog object reference
Animal animal = new Dog();

//dog variable is of type Dog (also an Animal)
//and initialized as a Dog object reference
Dog dog = new Dog();

animal.breath();
dog.breath();

//line below throws a compiler exception
//since animal is declared as type Animal
//not all Animals know how to bark
animal.bark();

//line below compiles fine
//since dog is declared as type Dog
//and Dog's know how to bark
dog.bark();
}
}

关于java - 父类(super class)引用不应该能够调用其子类独有的方法,但是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28800156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com