Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

casting

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...)

like image 416
BlackVegetable Avatar asked Jul 31 '12 16:07

BlackVegetable


People also ask

Can you put an if statement inside an object?

You can use an if statement, if it is within a immediately invoked function. Show activity on this post.

Can we write if condition in else?

The if/else if statement allows you to create a chain of if statements. The if statements are evaluated in order until one of the if expressions is true or the end of the if/else if chain is reached. If the end of the if/else if chain is reached without a true expression, no code blocks are executed.

How do you write the condition of an object?

To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.

Can you cast an object in Java?

Type Casting in Java – An IntroductionType Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind of Object, and the process of conversion from one type to another is called Type Casting.


1 Answers

The problem here is that your syntax is not right. It should be

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;
    }
}
like image 111
Haozhun Avatar answered Sep 23 '22 08:09

Haozhun