In Java, a getter method is a method that returns the value of a class field. Getter methods are commonly used to provide access to private fields of a class, while still protecting the fields from direct modification.
Here's an example of how you could define a getter method for a private field in a Java class:
public class MyClass { private String name; public String getName() { return name; } }
In this example, the getName()
method is the getter method for the name
field.
To use the getter method, you can create an instance of the MyClass
class and call the method on the instance. For example:
MyClass obj = new MyClass(); String name = obj.getName();
Getter methods are typically named using the Java Bean convention, where the getter method starts with "get" followed by the name of the field in camel case. For example, if the field name is "firstName", the getter method would be named "getFirstName()".
You can also use the @Getter
annotation from the Lombok library to automatically generate a getter method for a field. This can make your code more concise and easier to maintain.
import lombok.Getter; @Getter public class MyClass { private String name; }
In this example, the @Getter
annotation will generate a getName()
method for the name
field. You can then use the getter method as described above.