-3

I have to guess the output for this code sequence:

Circle c1 = new Circle(5);
Circle c2 = new Circle(5);
Circle c3 = new Circle(15);
Circle c4 = null;
System.out.println(c1==c1);
System.out.println(c1==c2);
System.out.println(c1==c3);
System.out.println(c1.equals(c1));
System.out.println(c1.equals(c2));
System.out.println(c1.equals(c3));
System.out.println(c1.equals(c4));

If I guess it by head I get:

true false false false true true false false

If I cheat and compile it I get:

true false false false true false false false

So my question is, is

System.out.println(c1.equals(c2));

true or false?

pyuntae
  • 742
  • 3
  • 10
  • 25

2 Answers2

2

It depends on your class Circle.

c1.equals(c2) is really just calling the method "equals" of your class Circle on the object c1 with the argument c2. If there is a custom implementation of this method, one might expect it to return true. If there is none, it will default to the superclass (Object) declaration of equals, which is the same as using the "==" operator.

public boolean equals(Object obj) {
    return (this == obj);
}
Valette_Renoux
  • 366
  • 1
  • 9
2

To add to the existing answer, if you want to override the .equals() method, you typically make the equality based on some property of the object. Based on my understanding, you want circles to be equal if and only if they have equal radii.

If you have a .getRadius() function, then a sample .equals() method definition would be

@Override
public boolean equals(Object o) {
    if(o == null) {
        return false;
    } else if (!(o instanceof Circle)) {
        return false;
    } else {
        return this.radius == ((Circle) o).getRadius();
    }
}

I will also add that whenever you override .equals(), you should also override .hashCode() so that whenever two objects are "equal", they also have the same hash code. For more information, this is a good read.

Community
  • 1
  • 1
M.S.
  • 1,091
  • 1
  • 11
  • 27
  • Good thought on this.radius. That is probably the best way to check equality in circles. If he doesn't already have that implemented, it should be. Upvoted for that. – Ashwin Gupta Mar 06 '16 at 18:45