Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes Hierarchy and Casting between Objects

Tags:

java

casting

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?

like image 412
jnardiello Avatar asked Jun 01 '26 15:06

jnardiello


1 Answers

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.

like image 195
Zim-Zam O'Pootertoot Avatar answered Jun 04 '26 03:06

Zim-Zam O'Pootertoot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!