Why can't I create an object inside an if statement?

I have not seen the exact question here that surprises me.

The following commands 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; } } 

While changing this in order to drop the object and keep its reference in the new object outside the conditional statement, the problem is fixed:

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

My question is: why is this behavior prohibited in Java? (Java 5 specifically)

EDIT: Yeah! Thank you all. Trim modern IDEs giving vague error messages. I began to throw them off, which this time did not help me. (Netbeans warned me about all the missing brackets and there was no semicolon ...)

+6
source share
6 answers

The problem is that your syntax is incorrect. 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; } } 
+17
source

I prefer the syntax

 Category.class.cast(o) 

then you explicitly state what you are doing and avoid confusion with parentheses. In my opinion, this is the same as ((category) o)

+3
source

This should be allowed, it seems your brace might be off: you tried something like

if (this.order <(((Category) o) .order))

+1
source

I think you need this:

 (((Category) o).order) 

I just tried a simpler version of what you have:

 int a = 5; if(4 < (double)a); 

and it compiled perfectly.

+1
source

There is a clear difference between the two pieces of code that you posted:

 (Category o) 

differs from:

 ( Category )o 

This first will not compile, the second will.

+1
source

Check out a simple working casting demo in if :

 int i; float d = 10.5f; if((i = (int) d) == 10){ //works } 

in your code problem there is if ( this.order < ((Category o).order) ) operator is wrong

it should be if ( this.order < ((Category) o).order)

EDIT: Your problem is solved, but one thing is bigger ( extra vertex ), you don't need to have else ( ladder form ), since you have return inside if

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

Source: https://habr.com/ru/post/921783/


All Articles