-3

I am not really sure why I should use getter in this case. Consider the following example:

public class Coin {

    private String sideUp;


    Coin() {
        sideUp = "heads";
    }

    protected String getSideUp() {
        return sideUp;
    }


    protected void toss(String sideUp) {
        // some code to randomly decide heads or tails
        this.sideUp = sideUp;
    }


    public static void main(String[] args) {
        Coin coin = new Coin();
        System.out.printf("Initial side %s\n", coin.sideUp);
        // System.out.printf("Initial side is %s\n, coin.getSideUp);

        coin.toss(coin.sideUp);
        // coin.toss(coin.getSideUp);

        System.out.printf("Side Up is %s\n", coin.sideUp);
        // System.out.printf("Side Up is is %s\n, coin.getSideUp);
    }
}

What is the difference between coin.SideUp and coin.getSideUp? Is it rather the question of different approach in this case?

KurodaTsubasa
  • 25
  • 2
  • 5
  • `coin.sideUp` will not give you the value of `sideUp`, this is because you declared it as a `private` variable. `private` variables are only accessible in the class they are defined in. So, for this particular case you WOULD need a "getter" method. – chRyNaN May 04 '13 at 21:56

1 Answers1

2

Using a getter in this case prevents an outside class from changing its value except through the toss method. In this case it's a good decision, since it clarifies that it can only be changed through using toss. If this is the only purpose, however, why not just make toss return the proper String?

nullptr
  • 2,244
  • 1
  • 15
  • 22
  • Thanks for the quick answer. So, in general, it is a good practice to access the value using getter, right? Thank you for your suggestion, but I have specifically written this code on purpose to clarify the question about the getter. – KurodaTsubasa May 04 '13 at 21:36
  • @user2115641 Yes, it's generally good practice to use getters and setters, just in case you want to change the implementation. It can also tell you something about how the class is supposed to be used, like in this case. – nullptr May 04 '13 at 21:38