class Deneme{
public static void main(String[] args) {
Object circle1 = new Circle();
Object circle2 = new Circle();
System.out.println(circle1.equals(circle2));
}
}
class Circle{
double radius;
public boolean equals(Circle circle) {
return this.radius == circle.radius;
}
}
And
class Deneme{
public static void main(String[] args) {
Object circle1 = new Circle();
Object circle2 = new Circle();
System.out.println(circle1.equals(circle2));
}
}
class Circle{
double radius;
@Override
public boolean equals(Object circle) {
return this.radius == ((Circle)circle).radius;
}
}
I am having issues with those codes. I have two questions. Firstly, In the first example I know equals() is not overridden. In the main method I created circle1 and circle2 objects whose declared types are Objects. And then we invoke equals() method but equals() method only take parameters whose declared types are Circle. How can it be possible? The code is running without any problems.
Secondly when i tried to run the codes i got "false" for the first example and "true" for the second in the console. Can you explain the logic behind those codes? What are we trying to prove here? What has changed when i changed the signature of equals() method from Circle circle to Object circle?
When overriding equals try the following. It is necessary to check for null values and improper types to prevent NPE's
and casting exceptions
.
class Circle{
double radius;
@Override
public int hashCode() {
return Double.valueOf(radius).hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Circle) {
Circle circle = (Circle)obj;
return this.radius == circle.radius;
}
return false;
}
}
The main point to remember is that the type of the equals method is Object
, not your class type
.