0

I just wrote a little test program:

public class ClassField {
    int a = 10;

    public int getValue() {
        return a;
    }

    public void setValue(int a) {
        this.a = a;
    }
}

public class Main {
    public static void main(String[] args) {
        ClassField test1 = new ClassField();
        ClassField test2 = new ClassField();

        System.out.println(test1.getValue());
        test1.setValue(20);
        System.out.println(test1.getValue());

        System.out.println(test2.a);
        test2.a = 20;
        System.out.println(test2.a);
    }
}

The program gave out the output as expected:

10
20
10
20

As I realised, there were 2 ways of accessing the fields: by accessing it directly, and by accessing it indirectly through a method. Which way is generally considered as better?

Shadow
  • 3,926
  • 5
  • 20
  • 41
code_unknown
  • 33
  • 10

1 Answers1

1

Generally speaking, methods are a better way to access any field because you only get the value of the variable, not the variable itself. It also provides a means of restricting the access to the variable, whether getting, setting, or both. This idea is more prevalent in C++, due to its capacity use of references, but the practice carries over to other Object-Oriented languages. Methods also tend to provide a more intuitive API when other programmers are involved.

Elenian
  • 144
  • 4
  • 7