-3

When it comes to Java programming you'll stumble upon this along your way. Here is an elementary answer to help new programmer learn how to use a getter method without the terminology or complexity of people is this field.

Lea
  • 97
  • 2
  • 14

1 Answers1

1

By creating an accessor method (and not creating a mutator method).

public class MyClass {
  public MyClass(int v) {
    this.myField = v;
  }
  private int myField;
  public int getMyField() {
    return myField;
  }
}

Then you can call that "getter" in some other class with an instance of MyClass.

public class SomeOtherClass {
  public static void doSomething(MyClass my) {
    System.out.println(my.getMyField());
  }
  public static void main(String[] args) {
    doSomething(new MyClass(42)); // <-- for example.
  }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249