I'm trying to cast the fourth equals trough cast between double and Figura class but i don't know how to resolve. I'm trying to cast the fourth equal to trough cast between the double and the Figura class, but I don't know how to do it.
The exercice says: Given the Figura class that counted the String color attributes, String nom and the double area() method, the equals method has been defined as follows: Modify the equals method so that if the unchecked ClassCastException is produced, it is still captured and processed in the method because it behaves with the equals defined in the Object class.
package ejer2;
public class Main {
public static void main(String[] args) {
Figura f1 = new Figura("roig","quadrat");
Figura f2 = new Figura("roig","quadrat");
Double d = new Double(1.0);
String k = "Hola";
boolean b1 = f1.equals(f2);
boolean b2 = d.equals(k);
boolean b3 = k.equals(f2);
boolean b4 = f1.equals(d);
}
}
package ejer2;
public class Figura {
String color;
String nom;
public Figura(String color, String nom) {
this.color=color;
this.nom=nom;
}
public double area() {
return 0;
}
public boolean equals (Object o) {
Figura f =(Figura) o;
try {
return this.color.equals(f.color) && this.nom.equals(f.nom)&& this.area() == f.area();
}
catch(ClassCastException ex) {
return this.color.equals(f.color) && this.nom.equals(f.nom);
}
}
}
CodePudding user response:
Every class in Java derives from the Object
class, this includes Double
so you don't need to cast it at all. In your equals
function, you should only cast once you're sure it's a valid Figura
object using instanceof
public boolean equals (Object o) {
if(!o instanceof Figura) {
return false;
}
//now we can safely cast because we know it must be a Figura object
Figura f = (Figura) o;
}
In Java 14 (preview) and upwards you can also use smart casts
public boolean equals (Object object) {
if(object instanceof Figura o) {
/* object is now guaranteed to be
of type Figura and we have a new reference to the automatically casted object "o" */
}
}