In the example below (from my coursepack), we want to give to the Square
instance c1
the reference of some other object p1
, but only i
Because this particular syntactic sugar is not yet added to the language. I think it was proposed for Java 7, but it doesn't seem to have entered project coin
The compiler does not infer that since you are in the block, you have done a successful check for the type of the object. An explicit cast is still required to tell the compiler that you wish to reference the object as a different type.
if (p1 instanceof Square) {
// if we are in here, we (programmer) know it's an instance of Square
// Here, we explicitly tell the compiler that p1 is a Square
c1 = (Square) p1;
}
In C# you can do the check and the cast in 1 call:
c1 = p1 as Square;
This will cast p1
to a Square, and if the cast fails, c1 will be set to null
.
E.g. If you hand over p1 as of type Object, the compiler wouldn't know that it is in fact an instance of Square, so that Methods etc. wouldn't be accessible. The if simply checks for a certain type to return true/false, but that doesn't change the type of the variable p1.
The test is done to prevent from ClassCastExceptions
at runtime:
Square c1 = null;
if (p1 instanceof Square) {
c1 = (Square) p1;
} else {
// we have a p1 that is not a subclass of Square
}
If you're absolutly positive that p1
is a Square
, then you don't have to test. But leave this to private methods...
There's a difference between measuring if some object will fit in a box, and actually putting it in the box. instanceof
is the former, and casting is the latter.
The implied cast feature is justified after all but we have trouble to implement this FR to java because of backward-compatibility.
See this:
public class A {
public static void draw(Square s){...} // with implied cast
public static void draw(Object o){...} // without implied cast
public static void main(String[] args) {
final Object foo = new Square();
if (foo instanceof Square) {
draw(foo);
}
}
}
The current JDK would compile the usage of the second declared method. If we implement this FR in java, it would compile to use the first method!