Get set in Groovy

Find this useful? Support us: Star on GitHub 6
Category: Class | Language: Groovy

In Groovy, get/set methods provide a way to access and modify properties of a class. Here's an example:

class Person {
    private String name
    private int age

public String getName() {
return name
}

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

public int getAge() {
return age
}

public void setAge(int age) {
this.age = age
}
}

In this example, the Person class has two properties: name and age. For each property, there is a get method to retrieve the value and a set method to modify the value. The get methods have a return type that matches the type of the property, and the set methods take a parameter of the same type.

Here's an example of how to use the Person class:

def person = new Person()
person.setName("Alice")
person.setAge(30)
println("Person name: ${person.getName()}, age: ${person.getAge()}") // Output: Person name: Alice, age: 30

In this example, we create a new Person object, set the name and age properties using the set methods, and then retrieve the values using the get methods.

Alternatively, in Groovy, we can directly access the properties of the class, instead of using the get/set methods, like shown below:

class Person {
    String name
    int age
}

def person = new Person(name: "Alice", age: 30)
println("Person name: ${person.name}, age: ${person.age}") // Output: Person name: Alice, age: 30

This way of accessing properties is achieved by default property accessors generated by Groovy for classes that don't have get/set methods.