Reputation: 153
As per an assignment, I have to create a method called "equals" to do the following:
The method compares the instance variables of the calling object with instance variables of the parameter object for equality and returns
true
if the dollars and the cents of the calling object are the same as the dollars and the cents of the parameter object. Otherwise, it returnsfalse
.
UPDATE: I made a mistake and put the wrong thing, updated it. Got a new error:
Money.java:115: error: long cannot be dereferenced
if (dollars.equals(otherObject.dollars) &&
^
Money.java:116: error: long cannot be dereferenced
cents.equals(otherObject.cents))
^
2 errors
With the method:
public boolean equals(Money otherObject)
{
boolean status;
if (dollars.equals(otherObject.dollars) &&
cents.equals(otherObject.cents))
return status = true;
else
return status = false;
}
Upvotes: 1
Views: 2296
Reputation: 3822
So both of your errors are trying to tell you that for whatever reason, your Money
class doesn't have a field called symbol
. So I'd confirm what the name of that field is before anything else and correct that.
You also need a return status;
line, as outlined in the comments below your question.
Finally, and perhaps requiring the biggest change of all, you don't have the method signature for equals()
correct. As you can see from the JavaDoc, the method is meant to take an Object
as a parameter, not another instance of Money
. Typically you'd do something like the following:
@Override
public boolean equals(Object object) {
if (object == null || !(object instanceof Money)) {
return false;
}
Money other = (Money) object;
return this.value.equals(other.value)
&& this.secondField.equals(other.secondField)
&& this.primitiveField == other.primitiveField;
}
Since primitive types (int
s, long
s, etc.) don't have any methods on them (including .equals()
, you have to compare these fields using ==
rather than .equals()
, as shown in the example above.
This isn't the most complete solution (there's plenty of good information answering this question), and you should also override Object.hashCode()
if you're modifying equals()
, to keep them consistent.
Upvotes: 1
Reputation: 167
Are dollars
and cents
primitive long
types?
You'd want to use (dollars == otherObject.dollars) && (cents == otherObject.cents) if they are. You can't call a method (such as equals()
) on a primitive.
Upvotes: 1