1

Related to: What does casting do at compiler/machine level?

Let's say I have custom types. Type A is a subtype of Type B.

Originally, my variable is typed ad Type A. Then I cast it to Type B.

Do most compilers, Java's in particular, retain any "memory" of the fact that the variable was once of Type A? And therefore operations that are specific to variable of Type A are still valid for a variable of Type B?

// Thanks all for your comments. Is it possible to call subclasses' methods on a superclass object? - I found my answers here. I don't think I asked the right question originally but everyone's helpful comments led me to thinking about the question in a different way and eventually getting my answers.

Community
  • 1
  • 1
the_rj
  • 141
  • 6

3 Answers3

1

Casting essentially says "pretend this variable is of this type just for this call". The underlying variable/object is not changed and does not lose its type declaration. Java is a statically, strongly typed language.

nameless912
  • 367
  • 1
  • 12
  • This is correct for objects but does not apply to primitive types. – dotvav Jul 31 '15 at 16:09
  • Casting a primitive type generates an entire new value though, doesn't it? which makes it kind of a moot point either way. – nameless912 Jul 31 '15 at 16:10
  • Hmm... I don't think I asked the right question. Let's say I have Custom Type A, which is a subclass of Custom Type B. I create variable x of Type A. Then I assign variable y to (Type B)x, thereby assigning y to the up-casted version of x. Should I be able to use x's type-specific methods to manipulate y? – the_rj Jul 31 '15 at 16:52
  • @the_rj Please create some code that shows what you mean. If A is a subclass of B, then a variable of type A has access to both A and B's methods. But it's unclear what the original type of your `y` variable was. – nos Jul 31 '15 at 17:09
1

The compiler does not retain information after the cast, it simply assumes you know what you are doing. The object itself however is unchanged after the cast. All objects contain a reference to their Class internally that is accessible via Object#getClass(). At runtime during the cast the virtual machine verifies the cast is valid by checking compatibility of the Classes and throws ClassCastException if it is not a valid cast.

satur9nine
  • 13,927
  • 5
  • 80
  • 123
0

You should really try it, but in the case you've posted, the compiler won't catch it. It will error at Runtime.

However I believe if you tried to do something like this:

String foo = "Hello";
Integer val = (Integer) foo;

I think the compiler will catch that, since a String can never be an Integer

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80