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

时间:2017-12-15 21:57:04

标签: java casting polymorphism

假设我有3个班级:

  • 超级课程是:Animal
  • 有一个继承Dog
  • 的子类Animal
  • 有一个继承Cat
  • 的子类Animal

现在,如果我这样做:Animal a = new Dog();

Dog指向的对象a是否会转换为Animal

如果是,那么这会将变量和对象都投射到狗吗?

((Dog)a).bark(); // bark() is specific for the Dog

在Java中转换这些引用类型的规则是什么?

1 个答案:

答案 0 :(得分:1)

我将尝试描述背景中发生的事情,希望能够清除某些事情。 让我们打破这个宣言&定义为部分。

  1. '一个'被宣布为动物。
  2. '一个'被定义为狗。
  3. Dog扩展Animal,因此,动物方法(包括构造函数)得到定义。
  4. 定义Dog方法,同时覆盖父类Animal定义的任何方法,并掩盖父类的成员变量。
  5. 在查看' a'时,您正在使用' Animal'透视,因此您无法使用仅由Animal的子类声明的任何方法(或字段)。为了获得"你可以完全像你一样从动物到狗的视角。请记住,向下倾斜是不安全的,而向上倾斜则是。

    例如:

    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. 
    

    通常,一个好的做法是为Animal创建一个抽象类,然后用子类覆盖它的一些方法。 例如:

    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");
      }
    }