向上倾斜向下倾斜 [英] Upcasting Downcasting

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

问题描述

我有一个父类类A 和一个子类类C扩展A

I have a parent class class A and a child class class C extends A.

A a=new A();
C c=(C)a;

这给了我错误。为什么?

This gives me error. Why?

此外,如果我的代码是

A a=new A();
C c=new C();
c=(C)a;

一切正常。

现在是什么所有方法都可以我的 c 变量访问... C中的那些或B类中的那些?

Now what all methods can my c variable access..the ones in C or the ones in class B?

推荐答案

它给你一个错误,因为一个 不是一个 C的实例 - 所以你不能让它垂头丧气。想象一下,如果 允许 - 你可以这样做:

It's giving you an error because a isn't an instance of C - so you're not allowed to downcast it. Imagine if this were allowed - you could do:

Object o = new Object();
FileInputStream fis = (FileInputStream) o;

当您尝试从流中读取时,您会发生什么?你期望从哪个文件中读取?

What would you expect to happen when you tried to read from the stream? What file would you expect it to be reading from?

现在是第二部分:

A a=new A();
C c=new C();
C c=(C)a;

这将正常工作 - 一开始它甚至不会编译,因为你两次声明相同的变量( c );如果您修复了这个错误,当您尝试将 A 的实例强制转换为 C <时,仍会获得异常/ code>。

That will not work fine - for a start it won't even compile as you're declaring the same variable (c) twice; if you fix that mistake you'll still get an exception when you try to cast an instance of A to C.

此代码真的有效:

A a = new C(); // Actually creates an instance of C
C c = (C) a; // Checks that a refers to an instance of C - it does, so it's fine

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

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