Reference type conversions - 1

"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
String s = "mom";
Object o = s; // o stores a String
A typical widening reference conversion
Object o = "mom"; // o stores a String
String s2 = (String) o;
A typical narrowing reference conversion
Integer i = 123; // o stores an Integer
Object o = i;
Widening conversion.
Object o = 123; // o stores an Integer
String s2 = (String) o;
Runtime error!
You cannot cast an Integer reference to a String reference.
Object o = 123; // o stores an Integer
Float s2 = (Float) o;
Runtime error!
You cannot cast an Integer reference to a Float reference.
Object o = 123f; // o stores a Float
Float s2 = (Float) o;
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 exampleswe have a way to find out what type is referenced by the Object variable:"

Code
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."