Shantanu Nandan
Shantanu Nandan

Reputation: 1462

overriding equals method in java but getting logical errors/unexpected results

In this program i was trying to compare the field value of two reference variable value by overriding equals method---- Here is the code----

public class D {
int i,j;

 D(int i,int j)
 {
     this.i=i;
     this.j=j;
 }
 public boolean equals(Object f)
 {
    boolean s= (this.i==((D)f).i);
    boolean n= (this.j==((D)f).j);
    return s==n;
 }
}

public class run02 {
 public static void main(String[] args){
 D d=new D(4,5);
 D d1=new D(6,7);
 D d2=new D(8,10);
 System.out.println(d.equals(d1));//comparing reference variable value
 System.out.println(d1.equals(d2));//comparing reference variable value
 System.out.println(d);//printing reference variable memory address
 System.out.println((d==d1));//comparing reference variable memory address
 }
}

Output-true//comparing reference variable value
       true//comparing reference variable value
       firstProg.e@g3h742//memory address
       false//comparing reference variable memory address

When i was trying to create a method public boolean equals(int i, intj) without giving return value then java throws compilation error.

Upvotes: 0

Views: 207

Answers (2)

saurav
saurav

Reputation: 3462

When i was trying to create a method public boolean equals(int i, intj) without giving return value then java throws compilation error.

Yes it will give you a compilation error because you are trying to cheat compiler, as in the method signature you are promising the compiler that at the end you will give it a boolean but in the end you are giving it anything. So, that's why the compiler is complaining.

Upvotes: 2

rgettman
rgettman

Reputation: 178253

The problem lies in this line:

return s==n;

Here, this will return true if both s and n are false.

You should use s && n to return true only if both s and n are true.

Upvotes: 12

Related Questions