首页 > 解决方案 > 在 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 的类到底是什么?

标签: javainheritancereference

解决方案


根据您的代码,您应该将 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 而不是编译器决定的,它被称为运行时多态性。


推荐阅读