0

Why does there need to be downcasting in this code?

class A { private int x; public boolean equals(Object o) { return ((A)o).x == this.x; } public static void main(String[ ] args) { A a = new A(); a.x = 9; A b = new A(); b.x = 5; System.out.println(a.equals(b)); } } I don't get why just typing "return o.x == this.x;" doesn't work.

2nd Jun 2018, 5:08 AM
Joshua Franco Pili
Joshua Franco Pili - avatar
5 ответов
+ 4
The equals method is checking whether the values contained in the A objects are the same to see if they are identical. Using == would check if the A object referenced the same object in memory not if they were identical. The casting in the equals method isn't really needed in this case. The code below will accomplish the same task without any casting. public boolean equals(A a) { return a.x == this.x; }
2nd Jun 2018, 5:44 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Dan Walker- Thank you for the link.
2nd Jun 2018, 7:49 AM
ODLNT
ODLNT - avatar
+ 1
Why are passing o as an Object type as opposed to an A type? Any way Object o does not have a property name x and that's why you have cast it as an A type. You should be passing o as A type.
2nd Jun 2018, 5:57 AM
ODLNT
ODLNT - avatar
+ 1
ODLNT My guess would be that the OP is overriding the equals method which takes an Object https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object) which is actually advisable for any object you create, when you want a custom way of deciding equality. Joshua Franco Pili so your code is almost correct! A good way to write equals methods to return false for a null input (which will currently throw a NullPointerException) and then check if (o instanceof A) { A castObj = (A) o; return castObj.x == this.x; } else { return false; } (I wrote it that way in case you want to add more variables, you can compare on the cast version instead). The object itself never actually changes type, but the equals method only assumes the attributes that Object can have, downcasting is you telling the program "this is actually of this type". So Object has no attribute x, but if you say "this is really an A" then you have access to the visible members of A
2nd Jun 2018, 7:31 AM
Dan Walker
Dan Walker - avatar
+ 1
Joshua Franco Pili- It appears that I lept before looking, my apologies.
2nd Jun 2018, 7:48 AM
ODLNT
ODLNT - avatar