getter and setter in java

https://w‮al.ww‬utturi.com
getter and setter in java

In Java, a getter method is a method that returns the value of a class field, and a setter method is a method that sets the value of a class field. Getter and setter 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 and setter method for a private field in a Java class:

public class MyClass {
  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

In this example, the getName() method is the getter method for the name field, and the setName() method is the setter method for the name field.

To use the getter and setter methods, you can create an instance of the MyClass class and call the methods on the instance. For example:

MyClass obj = new MyClass();
obj.setName("John");
String name = obj.getName(); // name will be "John"

Getter and setter methods are typically named using the Java Bean convention, where the getter method starts with "get" and the setter method starts with "set", 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()" and the setter method would be named "setFirstName()".

You can also use the @Getter and @Setter annotations from the Lombok library to automatically generate getter and setter methods for a field. This can make your code more concise and easier to maintain.

Created Time:2017-11-01 12:05:01  Author:lautturi