Hi, I am attempting to check if two die are equal to eachother and im having a bit a trouble.
So far i have been given code in the DiceSimulator class that creates an object for each die
Now i have been having trouble with an equals method in the Die class. So far I have this and i am getting the error that die1 and die2 cannot be resolved. Any ideas? I have a feeling this is a quick fix.
Harsha's code also highlights another flaw in your original code. The equals method requires java.lang.Object as its parameter type. If it's something else you're not overriding the equals method but overloading it instead.
And if you're overriding equals you should also override hashCode.
Matthew Brown wrote:I think he means the use of instanceof. Using that in an equals() method can lead to problems unless the class or the method is final. Think about how you might implement equals() in a subclass.
Oh, OK. I don't really think of that as a potential error, because using getClass() can cause other problems, such as violating LSP; and you have to use one or the other (unless you want to get quite involved). Personally, I always use instanceof unless I've got a good reason not to.
Campbell Ritchie wrote:If you make the class final, then there is no such problem either.
Yeah. That one actually solves a lot of problems.
In fact, I don't know why more schools don't recommend getting into the habit of doing it as a matter of course (like making variables private). After all, you can always remove it later on if it's too restrictive.
Joined: Oct 13, 2005
I suspect that a lot of teachers don’t know about final.