Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Java
public class Foo{
   private int data;

   public boolean equals(Object other){
     if(!(other instanceof Foo)){
         return false;
     }
     Foo f = (Foo) other; 
     return this.data == f.data;
   }
}

I can't understand it, I don't know why we should cast the object if, it is a instance of Foo there is no need to cast it

What I have tried:

I can't understand it, I don't know why we should cast the object if, it is a instance of Foo there is no need to cast it
Posted
Updated 8-May-18 10:00am
v3

Indeed, you know for sure that other is a Foo because otherwise, the method would have returned false already.

The compiler, however, doesn't know that - it just follows the instructions you give it, it does not "reason" about your code. For the compiler it's just an Object that you have to cast to a Foo before you can use Foo fields, because, again, it does not try to reason about your logic.
 
Share this answer
 
Comments
Maciej Los 8-May-18 16:00pm    
5ed!
Thomas Daniels 8-May-18 16:00pm    
Thank you!
If you don't cast other to type Foo, you won't be able to access the members of the Foo class. Yo have only access to what Object class exposes. After all the parameter is defined as Object.
 
Share this answer
 
Comments
Maciej Los 8-May-18 16:00pm    
5ed!
Well... Java equals() Method[^] determines whether an object that invokes the method is equal to the object that is passed as an argument.

The reason of casting other object as Foo is one, the most important: you have to determine if other is type of Foo to be able to compare data (Foo's member). That's all!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900