Solved! Quick Java question.

Amol S.

Platinum Member
Mar 14, 2015
2,570
779
136
Note that whenever I say classA, I am referring to a abstract class that is the parent of a regular class that is called classB.
Is the bellow code:
Java:
classB b = new classB();
classA refer = b;

the same as:

Java:
classA refer = new classB();

or are they both different?
 
Solution
They are functionally equivalent.

The type in java enforces that the assigned value is the same type or subtype. It does not do any sort of conversion. What's actually stored is the reference value.

This is why this is safe

Code:
Integer a = 1;
Number b = a;
Integer c = (Integer)b;

The only allocation that happened is the initial boxing assignment of a. After that, java is just setting b and c to the a reference.

This is also why this is invalid
Code:
Integer a = 1;
Number b = a;
Double c = (Double)b;

That's because Double is not a subtype of integer so the JVM is not capable of doing that assignment.

The rules around primitive types are different ( int i = (double)4.2; is valid). However, for all objects, they are consistent.

Cogman

Lifer
Sep 19, 2000
10,284
138
106
They are functionally equivalent.

The type in java enforces that the assigned value is the same type or subtype. It does not do any sort of conversion. What's actually stored is the reference value.

This is why this is safe

Code:
Integer a = 1;
Number b = a;
Integer c = (Integer)b;

The only allocation that happened is the initial boxing assignment of a. After that, java is just setting b and c to the a reference.

This is also why this is invalid
Code:
Integer a = 1;
Number b = a;
Double c = (Double)b;

That's because Double is not a subtype of integer so the JVM is not capable of doing that assignment.

The rules around primitive types are different ( int i = (double)4.2; is valid). However, for all objects, they are consistent.
 
  • Like
Reactions: Amol S.
Solution