-17

Let's say I have a Money class that looks like this:

public class Money {
    private BigDecimal amount;
    private Currency currency;
}

I'd like to add two of these classes together, e.g.

Money m1 = Money(5);
Money m2 = Money(10);
Money m3 = m1+m2; // m3.amount should be 15

How would I write a method so that I could add together two of these Money classes?

Muz
  • 5,866
  • 3
  • 47
  • 65

1 Answers1

5

Java doesn't support operator overloading, instead you need to add an add function:

public class Money {
    private BigDecimal amount;
    private Currency currency;

    public Money add(Money m) {
        Money res = new Money();
        if (!currency.equals(m.currency)) {
            throw new UnsupportedOperationException();
        }
        res.currency = currency;
        res.amount = m.amount.add(amount);
        return res;
    }
}

Money result = one.add(two);
rubenwardy
  • 679
  • 5
  • 21
  • I'm not a big fan of returning null given mismatched currencies here; it's fine in the context of this question since OP is not concerned with it, but in practice there would ideally be a currency conversion method so that people using the Money class don't have to check for null so often. – Austin Schaefer Jul 21 '17 at 08:51
  • 1
    that is very true, edited – rubenwardy Jul 21 '17 at 08:53
  • Now you throw an Error? Really? What sense does that make? – Tom Jul 21 '17 at 08:56
  • 1
    I removed the `Error` part, because it was nonsense, as is "it's a programmer error". That kind of issue happens during runtime, on objects where the programmer has no control other them. That obviously a case for using `Exception`, not `Error`. – Tom Jul 21 '17 at 09:05
  • 1
    Thanks. Just needed to know that Java doesn't support it. The code was a little glitched so I updated it with what worked. – Muz Jul 21 '17 at 09:19
  • 2
    Be care with using `==` and `!=` on class objects, it usually compares references. The typo was that it should have been `equals` instead of `equal` – rubenwardy Jul 21 '17 at 09:22