Classes Hierarchy and Casting between Objects

泄露秘密 提交于 2019-12-12 12:26:59

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/17506587/classes-hierarchy-and-casting-between-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!