Мне нужна помощь, чтобы переопределить метод equals
. У меня все работает, кроме метода equals
. Метод equals
, который у меня есть, не дает мне правильного ответа. Я не могу понять, что может быть проблемой.метод равен - как переопределить
Мой класс:
package myclasses;
public class Currency
{
private int dollars, cents;
public Currency()
{
dollars = 0;
cents = 0;
}
public Currency(int d, int c)
{
this.dollars = d;
this.cents = c;
setCents(cents);
}
public int getDollars()
{
return dollars;
}
public int getCents()
{
return cents;
}
private void setDollars(int dollars)
{
this.dollars = dollars;
}
private void setCents(int cents)
{
while(cents > 99)
{
cents = (cents - 100);
dollars++;
}
this.cents = cents;
}
public void setAmount(int newDollars, int newCents)
{
setDollars(dollars);
setCents(cents);
}
public void add(int dollars, int cents)
{
this.dollars = dollars + getDollars();
cents = cents + getCents();
setCents(cents);
}
public boolean equals(Object dollars, Object cents)
{
if(this == dollars && this == cents)
return true;
if(!(dollars instanceof Currency) || !(cents instanceof Currency))
return false;
Currency money = (Currency) dollars;
Currency penny = (Currency) cents;
return (this.dollars == money.dollars) && (this.cents == penny.cents);
//return Currency.dollars.equals(Currency.cents);
//return this.equals(dollars) && this.equals(cents);
}
public boolean isZero()
{
if(getDollars() == 0 && getCents() == 0)
{
return true;
}
return false;
}
public String toString()
{
return "$" + getDollars() + "." +
(getCents() < 10 ? ("0" + getCents()) : getCents());
}
}
Вы понимаете, что 'equals' обычно используется для сравнения другой, как объект (т.е. это подпись должна быть' Equals (Object другой) ', то есть только один параметр – MadProgrammer