aspose file tools*
The moose likes Beginning Java and the fly likes override equals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "override equals" Watch "override equals" New topic
Author

override equals

abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635
I wrote a class myself , I want to override equals method in it.



error is missing return statement.

Did I override equals correct?
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11229
    
  16

Clearly if you get an error while compiling, you did not do something correct. Your primary error here is that there are ways that you can go through your code and never hit a return statement.

What happens if 'this' does NOT equal 'obj', and your obj IS an instance of equalsTest?

you'd skip your first if statement, skip the second one, and have nothing to return.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Rahul Sudip Bose
Ranch Hand

Joined: Jan 21, 2011
Posts: 637

you are getting the missing return statement. Why ? If for some reason the execution reaches the last if(-----) AND the condition inside that if evaluates to false then no value is returned. Suppose there was an else with the last if() and it returned a boolean, that error will go.

PS : Please give a short description of your code. It is easier to go through the code after reading some info rather than figuring out on my own.

Here is a remedy for such a situation :



That should make the compiler happy.

SCJP 6. Learning more now.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

abalfazl hossein wrote:

If obj == this then a == this and a.number == this.number per definition. You can replace the entire block by this:
The rest of the functionality, testing for number equality, should be done if the instanceof operator returns true - the part you're missing right now.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
David Byron
Rancher

Joined: Jan 20, 2009
Posts: 172

or simply


SCJD 6, OCPJP7, Baroque Potion, G+
abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635


At first I must be sure these objects has same type, Then check their fields

if this == obj , then equalsTest a=(equalsTest)obj; if a.number == this.number return true. Right?

But it has error, equal method does not check type of its parameter.for this line:



and has error for this:


Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

David Byron wrote:or simply

Which completely ignores checking for actual equality. You might as well not override equals and inherit the method from Object, which does the same.

Abalfazl, I think you want something like this:
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: override equals