Actually you don't have to cast it!
Am I making some newbie mistake
Yeap, but don't worry... after this you wont do it again ;)
See:
$cat Funky.java
class Funky {
}
class FunkySubClass extends Funky {
}
class SomethingElse {
}
class SomeClass extends SomethingElse {
private Funky aFunkyVar;
//...
public void noNeedToCast() {
aFunkyVar = new FunkySubClass();
}
}
$javac Funky.java
$
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:
int i = 255;
byte b = ( byte ) i;
If you don't cast the compiler will warn you, "hey, you don't really want to do that"
...
byte b = i;
...
Funky.java:18: possible loss of precision
found : int
required: byte
byte d = i;
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:
int i = 2550;
byte b = ( byte ) i;
System.out.println( b );
prints:
-10
You don't need to cast when the type is wider than the other type:
byte b = 255;
int i = b;// no cast needed
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:
java.lang.Object
|
+ -- Funky
|
+-- FunkySubclass
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:
void other( Object o ) {
// Cast needed:
Funky f = ( Funky ) o;
FunkySubClass fsc = ( FunkySubClass ) o;
FunkySubClass fscII = ( FunkySubClass ) f;
// Cast not needed:
Object fobj = f;
Object fscobj = fsc;
Funky fparent = fsc;
}
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.ClassCastException at 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.
:)
FunkySubClassis really a subclass ofFunky.