简体   繁体   English

在Java中使用多态时是否存在对象的隐式转换?

[英]Is there implicit cast of the object when using Polymorphism in Java?

Suppose I have 3 classes: 假设我有3个班级:

  • The super class is: Animal 超类是: Animal
  • There is 1 subclass Dog that inherits Animal 有1个子类Dog可以继承Animal
  • There is 1 subclass 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. 让我们将此声明和定义分成几部分。

  1. 'a' is declared as an Animal. “ a”被声明为动物。
  2. 'a' is defined as a Dog. “ a”被定义为狗。
  3. Dog extends Animal, therefore, animal methods (including constructor) get defined. Dog扩展了Animal,因此,对Animal方法(包括构造函数)进行了定义。
  4. Dog's methods get defined, whilst overriding any method that was defined by the parent class Animal) and overshadowing member variables of the parent class. Dog的方法得到了定义,同时覆盖了由父类Animal定义的任何方法,并遮盖了父类的成员变量。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM