Java中的上/下流 [英] Upcasting/Downcasting in Java

查看:138
本文介绍了Java中的上/下流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解Java中的向上转换和向下转换,并且对以下情况(关于我的代码,在下面)感到困惑:

I am trying to understand upcasting and downcasting in Java and I am confused by the following scenario (about my code, which is below):

首先-为什么当我包含行myAnimal.bark();

First - why is it that the code does not compile when I include the line myAnimal.bark();,

和第二个-(假设我注释了myAnimal.bark();)为什么调用myAnimal.move()打印"moveDog"而不是"moveAnimal"? myAnimal是否不限于Animal类中的方法,因为即使我们将其设置为Dog类型,我们也已将其声明为Animal?

and Second - (assuming I comment out myAnimal.bark();) why does calling myAnimal.move() print "moveDog" instead of "moveAnimal"? Isn't myAnimal restricted to methods from the Animal class because we have declared its type to be Animal, even though we are setting it to a type of Dog?

任何帮助将不胜感激!这是代码:

Any help is greatly appreciated! Here is the code:

    public class Animal {
        public void move() {
            System.out.println("moveAnimal");
        }

       public static void main(String[] args) {
          Dog myDog = new Dog();
          Animal myAnimal = myDog;
          myAnimal.move();
          //myAnimal.bark();
       }
    }

    class Dog extends Animal {
        @Override
        public void move() {
           System.out.println("moveDog");
        }

        public void bark() {
            System.out.println("bark");
        }
    }


推荐答案

在这一行有隐式的上行:

With the implicit upcast at this line:

Animal myAnimal = myDog;

您没有做任何更改基础实例myDog的操作.您正在做的就是将其分配给继承树中一级更高级别的变量.有效地,这限制了只能调用Animal中定义的方法的方法,而不会改变这些方法的解析方式.

You are not doing anything to change the underlying instance myDog. What you are doing is assigning it to a variable of a type one level higher in the inheritance tree. Effectively, this restricts which methods can be called to only those defined in Animal, but does not change how those methods resolve.

因为您将可用方法限制为仅在父类Animal上定义的方法可用,所以编译器无法解析Dog#bark(),因为它是Dog的方法,并且变量myAnimal被定义为类型为Animal的类型,没有#bark方法.

Because you have restricted the methods available to only those defined on the parent class Animal, the compiler cannot resolve Dog#bark(), since it is a method of Dog, and the variable myAnimal is defined to be of type Animal which has no #bark method.

#move()AnimalDog的方法,因此可以解析,但可以解析为Dog上定义的方法,因为myAnimal仍引用Dog的实例,尽管沮丧.

#move() is a method of both Animal and Dog, so it resolves, but it resolves to the method defined on Dog, since myAnimal still refers to an instance of Dog, despite being upcast.

这篇关于Java中的上/下流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆