Why can't I cast an object inside of an if statement?

Viewed 2330

I haven't seen this exact question here, which surprises me.

The following will not compile:

public int compareTo( Object o )
{
    if ( this.order < ((Category o).order) )
    {
      return -1;
    }
    else if ( this.order > ((Category o).order) ) 
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

Whereas changing this to cast the object and store its reference in a new object outside of the conditional statement fixes the issue:

Category cat = ( Category )o;
if ( this.order < cat.order )
// Etc...

My question is, why is this behavior not allowed in Java? (Java 5 specifically)

EDIT: Aha! Thank you all. Darn modern IDEs giving vague error messages. I've begun to discount them, which didn't do me any good this time. (Netbeans was warning me about both a missing parenthesis and a missing semicolon...)

6 Answers
Related