类层次结构和对象之间的转换 [英] Classes Hierarchy and Casting between Objects

查看:103
本文介绍了类层次结构和对象之间的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,无法将超类的Object转换为子类的Object



更具体地说,给定下面的类和接口层次结构:



p。 Alpha是Beta和Gamma的超类

。 Gamma是Delta和Omega的超类

。界面In由Beta和Delta实现



在这种情况下,我定义了以下代码:

  Delta r; 
Gamma q;

这是否正确?

  r =(Delta)q; 

我可以将q投射到类型Delta,即使Delta是Gamma的子类吗?
我认为这是不可能的,我的教科书说不然。我已经搜索了很多,根据我是对的,这是教科书的错误。



我没有任何东西?

解决方案

p>这是合法的:

  Gamma q = new Delta 
Delta d =(Delta)q;

这将编译,但会给你一个运行时错误:

  Gamma q = new Gamma(); 
Delta d =(Δ)q;

在第一种情况下, q Delta ,因此您可以将其投放到 Delta 。在第二种情况下, q 是一个 Gamma ,因此您不能将其转换为 Delta 。



A Gamma Gamma 对象 Gamma 的子类的对象,例如a Delta 对象;当你把一个 Gamma 转换为 Delta 然后你告诉编译器 Gamma 变量是指 Delta 对象或 Delta 如果你错了,你会得到一个 ClassCastException )。对象本身的类型是不可变的 - 您不能在运行时将 Gamma 对象的类型更改为 Delta 对象,所以如果一个 Gamma 变量实际上是指一个 Gamma 对象,但你试图把它转换为 Delta 对象,那么你会得到一个运行时异常。


as far as i know it's not possible to cast an Object of a superclass into an Object of a subclass. This will compile but during runtime it will return an error.

More specifically, given the following Hierarchy of Classes and Interfaces:

. Alpha is a superclass for Beta and Gamma
. Gamma is a superclass for Delta and Omega
. Interface "In" is implemented by Beta and Delta

In this scenario i define the following code:

Delta r;
Gamma q;

Is this correct?

r = (Delta) q;

Can i cast q to type Delta even if Delta is a subclass of Gamma? I think this isn't possible, my text book says otherwise. I already searched a lot and according to this i'm right and this is an error from the textbook.

Am i missing anything?

解决方案

This is legal:

Gamma q = new Delta();
Delta d = (Delta)q;

This will compile but will give you a runtime error:

Gamma q = new Gamma();
Delta d = (Delta)q;

In the first case, q is a Delta, so you can cast it to a Delta. In the second case, q is a Gamma, so you cannot case it to a Delta.

A Gamma variable can refer to a Gamma object or to an object that is a subclass of Gamma, e.g. a Delta object; when you cast a Gamma to a Delta then you are telling the compiler that the Gamma variable refers to a Delta object or to an object that is a subclass of Delta (and if you're wrong then you'll get a ClassCastException). The types of the objects themselves are immutable - you cannot change the type of a Gamma object to a Delta object at runtime, so if a Gamma variable actually refers to a Gamma object but you then try to cast it to a Delta object then you'll get a runtime exception.

这篇关于类层次结构和对象之间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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