3

ok so i just found out that if you have a class with global variables you can call it in another class just by saying class.variable and now i'm very confused as to why getVariable and setVariable methods exist ever when they're already accessible

so let's say we have these two classes

public class MyClass {
    public int num;
    public String str;
    public MyClass (int num, String str) {
        this.num = num;
        this.str = str;
    }
    public int getNum () {
        return num;
    }
    public String getStr () {
        return str;
    }
}
public class test {
    public static void main (String[] args) {
        MyClass x = new MyClass (3, "string");
        System.out.println(x.num);
        System.out.println(x.str);
        System.out.println(x.getNum());
        System.out.println(x.getStr());
        x.num = 4;
        System.out.println(x.num);
    }
}

Both ways, it accesses the same data from the object and outputs the same thing. Is one way better practice than the other or are there certain cases where one of the ways won't work?

faris
  • 692
  • 4
  • 18
  • 1
    Just because you can do something, doesn’t mean you should. The class’s data members should be private/protected if there exists public getters. – AJNeufeld Mar 05 '18 at 05:33

1 Answers1

2

Short answer: encapsulation.

A major benefit is to prevent other classes or modules, especially ones you don't write, from abusing the fields of the class you created.

Say for example you can an instance variable int which gets used as the denominator in one of your class methods. You know when you write your code to never assign this variable a value of 0, and you might even do some checking in the constructor. The problem is that some else might instantiate your class and later assign the instance variable a value of 0, thereby throwing an exception when they later invoke the method that uses this variable as a denominator (you cannot divide by 0).

Using a setter, you write code that guarantees the value of this variable will never be 0.

Another advantage is if you want to make instance variables read only after instantiating the class then you can make the variables private and define only getter methods and no setters.

Michael Jeszenka
  • 109
  • 1
  • 1
  • 5