1

I'm just wondering if there's any difference between using the set and get method, and just using object.variableName to set and get? Thanks.

package hello;

public class Helloworld {

int num;

public static void main(String[] args) {
    Helloworld hello1 = new Helloworld();
    Helloworld hello2 = new Helloworld();

    hello1.num = 5;
    System.out.println(hello1.num);

    hello2.setNum(5);
    System.out.println(hello2.getNum());

}

void setNum(int i) {
    this.num = i;

}

int getNum() {
    return this.num;

}
}
Skillet
  • 237
  • 1
  • 4
  • 16
  • I think this has already been answered a number of times. The [following answer](http://stackoverflow.com/a/11970468/697630) is one of those examples of this question being answered before. – Edwin Dalorzo Apr 07 '15 at 20:38

3 Answers3

1

The main reason is encapsulation. You want your variables to be private and not modifiable directly by the user or client, because it may affect behavior in other parts of the system.

Lawrence Aiello
  • 4,560
  • 5
  • 21
  • 35
1

It's basically a best practice that has to do with the concept of encapsulation.

If you use the get and set methods you have greater flexibility later on if you decide to add some extra logic to the get or set method (e.g. validation).

In the case of a getter, you also prevent the using class from modifying the variable if it is a primitive.

wvdz
  • 16,251
  • 4
  • 53
  • 90
0

Because sometimes, the variables are private and cannot be accessed via obj.varname. In short: encapsulation.

To protect your program, you want variables to be private as often as you can, and sometimes a set method is better if you want to put in a check to see if it's a valid value or something like that.

Aify
  • 3,543
  • 3
  • 24
  • 43
  • Also you might later want to add limitations for the variable which can be checked upon setting the number. – touko Apr 07 '15 at 20:34
  • Isn't the idea of making variables private so that they can only be access in the same class? If the getter and setter methods can access those private variables, then why make them private? Thanks. – Skillet Apr 07 '15 at 20:36
  • @skillet The getter and setter can provide limited access to said variables, and/or can provide output based on what you want the user to see. – Aify Apr 07 '15 at 20:37