0

Im a beginner at Java and im told to make getters in a class to get the variables of objects. I forgot to call the getter methods, but this didnt seem to be a problem for the outcome of my code. Below i provided some of the code i made:

public class Money 

private final int euros;
private final int cents;

public int euros() {
    return this.euros;
}

public int cents() {
    return this.cents;
}


public Money minus(Money decreaser) {

    int NewEuros = this.euros - decreaser.euros;
    int newCents = this.cents - decreaser.cents;

im told the correctway to get the variables euros and cents from the decreaser object is to use the getters like so:

public Money minus(Money decreaser) {

    int NewEuros = euros - decreaser.euros();
    int newCents = cents - decreaser.cents();

both gave me the results i was looking for. So now i am left confused about the use of getters. Could someone explain me why i should use getters to get the variables of an object?

  • 1
    There's little point when you're dealing with a single small class. The benefit of getters is to control access from outside the class that owns the member variables. This is "encapsulation" - the other classes don't need to know the details of the implementation (it may be a stored integer or it may be calculated, but only the 'inside' of the getter would need to know that). So, giving your advisers the benefit of the doubt: they're getting you to adapt habits that will help in future. But me, I wouldn't bother in this simple case. – user16632363 Oct 08 '21 at 21:29
  • 1
    To take @user16632363 comment one step further: avoid getters where you can. [Tell, don't ask](https://martinfowler.com/bliki/TellDontAsk.html). – Robert Oct 08 '21 at 22:08

0 Answers0