I don’t understand why I need to cast member variables to the proper type when their types are already declared. For example:
public class SomeClass extends SomethingElse {
private Funky mFunkyVar;
// a whole bunch of other variables and methods
public void needToCast() {
mFunkyVar = (Funky) new FunkySubClass();
}
}
Am I making some newbie mistake or is this indeed idiomatic Java? In the above I’m assuming that FunkySubClass is indeed a subclass of Funky.
Actually you don’t have to cast it!
Yeap, but don’t worry… after this you wont do it again 😉
See:
No compilation errors.
EDIT
You can cast primitives and object references.
For primitives you “have” to cast, if you want to narrow the value.
For instance:
If you don’t cast the compiler will warn you, “hey, you don’t really want to do that”
Casting is like telling the compiler: “hey don’t worry, I know what I’m doing, ok?”
Of course, if you cast, and the value didn’t fit, you’ll get strange results:
prints:
You don’t need to cast when the type is wider than the other type:
For references works in a similar fashion.
You need to cast, when you want to go down into the class hierarchy ( narrow ) and you don’t need to cast when you want to go upper in the hierarchy ( like in your sample ).
So if we have:
You only have to cast, when you have a type upper in the hierarchy ( Object or Funky ) in this case. And you don’t have to, if you have a type lower in the hierarchy:
With primitives the JVM know how to truncate the value, but with reference no. So, if the casted value is not of the target type, you’ll get a
java.lang.ClassCastExceptionat runtime. That’s the price you have to pay, when you tell the compiler “I know what I’m doing” and you don’t.I hope this is clear enough and don’t confuse you.
🙂