3

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?

Community
  • 1
  • 1
jnardiello
  • 699
  • 8
  • 15

1 Answers1

5

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.

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69