java - 在 Java 中,引用子类引用的超类变量的实际类是什么?
问题描述
我还是 Java 的新手,我对 Java 如何处理引用子类引用的超类变量有点困惑。我有两节课:
public class Animal{
}
public class Dog extends Animal{
}
然后我创建了一个运行类,如下所示:
public class Run{
public void get_dog (Dog a){
System.out.println("got a dog");
}
public static void main(String[] args) {
Animal a_animal = new Dog(); //Create a Animal variable with Dog class
Run test = new Run();
System.out.println(a_animal.getClass().getSimpleName());
test.get_dog(a_animal); //This will not run
}
}
getClass().getSimpleName() 告诉我 a_animal 的类是 Dog。但是 test.get_dog(a_animal) 不会运行,说 get_name() 只会采用 Dog 类而不是 Animal 类。那么 a_animal 的类到底是什么?
解决方案
根据您的代码,您应该将 Animal 对象传递给 get_dog 方法,而不是 Dog 对象。您尝试过的方法称为 upcasting 。Parent 类的引用变量引用 Child 类的对象,如下所示。
Animal a_animal = new Dog();
我已经为您重新编写了一个代码来理解以下概念
public class Animal {
void run() {
System.out.println("An animal is running");
}
}
public class Dog extends Animal {
void run() {
System.out.println("Dog is running in 20kmph");
}
}
public class Run{
public static void main(String[] args) {
Animal a_animal = new Dog(); //Creating a reference variable of Animal class by referring to Dog class (upcasting)
a_animal.run();//
}
}
下面是结果
解释
我们通过 Parent 类的引用变量调用 run 方法。由于它引用了子类对象,并且子类方法覆盖了父类方法,因此子类方法在运行时被调用。
方法调用是由 JVM 而不是编译器决定的,它被称为运行时多态性。
推荐阅读
- python - 排序顺序搜索
- eval - Python - 存储函数定义以供以后使用
- visual-studio - 在 VS2019 中使用 GTK+ 时 ffiw64.c 中的读取访问冲突
- spring - 手动配置 Spring Boot Reactive Mongo
- android - google hangouts meet 的包名是什么?
- php - 无法访问属性 - Laravel
- ionic4 - 第一次执行时的 SQLite 性能
- php - PHP:为什么前 3 个数组值反复打印?
- json - Perl JSON 包无法加载 JSON 文件 -> 出现意外字符
- python - 计算一列中重复的数量并列出它们