【发布时间】:2017-03-22 05:34:42
【问题描述】:
当超类引用指向子类对象时,jvm类型在执行过程中是否将对象从子类型转换为超类型并将其存储在引用变量中?
class Animal {
void bark() {
System.out.println("Animal is barking");
}
}
class Dog extends Animal{
void bark() {
System.out.println("Dog is barking");
}
}
public class DynamicBinding {
public static void main(String[] args) {
Animal a = new Dog(); //does implicit type casting happens at this line?
a.bark();
}
}
【问题讨论】:
-
我不相信,不。至少在大多数情况下,编译器会静态分析您的代码并确定不需要强制转换。如果需要,它会坚持你手动添加它。因此,我不相信 JVM 会在运行时不断检查对象以确保它们的类型是正确的。
-
您不需要将类型强制转换为其超类型。
new B()是定义为A。 -
Dog 扩展了 A 或 Animal 类和
A a = new B();或Animal a = new Dog();?
标签: java casting type-conversion