[英]Is there implicit cast of the object when using Polymorphism in Java?
Suppose I have 3 classes: 假设我有3个班级:
Animal
超类是: Animal
Dog
that inherits Animal
有1个子类Dog
可以继承Animal
Cat
that inherits Animal
有1个子类Cat
继承了Animal
Now if I do this: Animal a = new Dog();
现在,如果我这样做: Animal a = new Dog();
Does the object Dog
that a
points to get casted to Animal
? a
指向的对象Dog
扔给Animal
吗?
If yes then does this cast both the variable and the object to dog? 如果是,那么这是否会将变量和对象都转换为dog?
((Dog)a).bark(); // bark() is specific for the Dog
Also what are the rules for casting these reference types in Java? 还有在Java中强制转换这些引用类型的规则是什么?
I will try to describe what happens in the background, in the hopes that it will clear some things. 我将尝试描述背景中发生的情况,希望它可以清除一些情况。 Lets break this declaration & definition into parts. 让我们将此声明和定义分成几部分。
When looking at 'a', you are using the 'Animal' perspective and for that reason you are not capable of using any methods (or fields) declared only by sub-classes of Animal. 当查看“ a”时,您使用的是“动物”透视图,因此,您不能使用仅由Animal子类声明的任何方法(或字段)。 In order to "gain" that perspective you can downcast from Animal to Dog exactly as you did. 为了“获得”这种观点,您可以像完全一样将“动物”降级为“狗”。 Keep in mind that downcasting is not safe whereas upcasting is. 请记住,向下转换并不安全,而向上转换则安全。
For example: 例如:
Animal a = new Cat(); // cats can mew
Animal b = new Dog(); // dogs can bark
(Dog)b.bark() // Unsafe but compiles and works.
(Dog)a.bark() // Unsafe but compiles and throws a run time exception.
In general, a good practice would be to create an abstract class for an Animal and then override some of it's methods with subclasses. 通常,一个好的做法是为Animal创建一个抽象类,然后用子类覆盖其某些方法。 For example: 例如:
public abstract class Animal {
abstract void makeNoise();
}
public class Dog extends Animal {
void makeNoise(){
System.out.println("bark");
}
}
public class Cat extends Animal {
void makeNoise(){
System.out.println("mew");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.