我正在准备加入SCJP,看起来我不了解类强制转换原则。
class Dog extends Animal
创建
Dog()
实例的第一种方法-制作Animal实例并将其投放到Dog(upcast):Animal a = new Dog();
Dog d1 = (Dog)a;
VS
创建
Dog()
实例的第二种方法-直接进行创建:Dog d2 = new Dog();
在这种情况下,
d1
和d2
对象之间有什么区别? 最佳答案
Animal a = new Dog();// a dog is created but it will be referred by reference of animal as dog is an animal
Dog d1 = (Dog)a;//now we know that this animal is Dog so we are casting it to dog.
Dog d2 = new Dog();// we are creating instance of dog which is referred by reference of Dog
在这种情况下,d1和d2对象之间有什么区别?
d1
和d2
只是引用dog,最终都将引用Dog的实例。没有区别
另请参阅
Polymorphism