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.
Asked
Active
Viewed 144 times
-3
-
1*"How do I access a getter method?"* - `instanceOfObject.nameOfMethod()` (may require parameters depending on the method definations). – MadProgrammer Jul 23 '15 at 00:35
-
1*"How do I create two constant data fields?"* - `{public/protected/private} static final [type] [NAME] = [value]` – MadProgrammer Jul 23 '15 at 00:35
-
1You might like to have a read through [Classes and Objects](https://docs.oracle.com/javase/tutorial/java/javaOO/index.html) – MadProgrammer Jul 23 '15 at 00:36
-
`YourClass instanceOfObject = new YourClass();` `YourClass` will probably want to be `public`. Have a look at the linked tutorials – MadProgrammer Jul 23 '15 at 00:44
-
By constant data fields, do you mean class members? – deezy Jul 23 '15 at 00:48
1 Answers
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