"And now, a short lesson from Diego. Brief and to the point. About reference type conversions."
"Let's start with Object variables. You can assign any reference type to such a variable (widening conversion). However, to make the assignment in the other direction (narrowing conversion), you must explicitly indicate a cast operation:"
Code | Description |
---|---|
|
A typical widening reference conversion |
|
A typical narrowing reference conversion |
|
Widening conversion. |
|
Runtime error! You cannot cast an Integer reference to a String reference. |
|
Runtime error! You cannot cast an Integer reference to a Float reference. |
|
Conversion to the same type. A narrowing reference conversion. |
"A widening or narrowing reference conversion doesn't change the object in any way. The narrowing (or widening) part specifically refers to the fact that the assignment operation includes (does not include) type-checking of the variable and its new value."
"This is the rare example where everything is clear."
"To avoid the errors in these examples, we have a way to find out what type is referenced by the Object variable:"
int i = 5;
float f = 444.23f;
String s = "17";
Object o = f; // o stores a Float
if (o instanceof Integer)
{
Integer i2 = (Integer) o;
}
else if (o instanceof Float)
{
Float f2 = (Float) o; // This if block will be executed
}
else if (o instanceof String)
{
String s2 = (String) o;
}
"You should perform this check before every widening conversion unless you are 100% sure of the object's type."
"Got it."
GO TO FULL VERSION