Wednesday, 30 January 2019

Groovy: Properties


When a Groovy class definition declares a field without an access modifier, then a public setter/getter method pair and a private instance variable field is generated which is also known as "property".

How to define a property?
A property is a member of the class that satisfies below conditions.

a.   A mandatory name
b.   An optional type
c.    An absent access modifier like public, protected or private
d.   One or more optional modifiers like static, final, synchronized

Groovy generates getter and setter methods to the properties.

HelloWorld.groovy
class Employee {
 String name
 int id
}

Employee emp1 = new Employee()
emp1.setName("Krishna")
emp1.setId(123)

println "id : ${emp1.getId()}, name : ${emp1.getName()}"

Output
id : 123, name : Krishna

As you see above application, Groovy provides getter and setter methods to the properties name, id.

If you access the properties directly by name outside the class, then the getter, setter methods will be called appropriately.


HelloWorld.groovy
class Employee {
 String name
 int id
 
 public String getName() {
  println "getName is called"
  return name;
 }

 public void setName(String name) {
  println "setName is called"
  this.name = name;
 }

 public int getId() {
  println "getid is called"
  return id;
 }

 public void setId(int id) {
  println "setId is called"
  this.id = id;
 }
}

Employee emp1 = new Employee()
emp1.name = "Krishna"
emp1.id = 123

println "id : ${emp1.id}, name : ${emp1.name}"

Output
setName is called
setId is called
getid is called
getName is called
id : 123, name : Krishna

Note
a.   If a property is final, then no setter method is generated.

No need to define the property, if you specify getters and setters
Groovy identifies the properties even if there is no backing field provided but you specify getters or setters explicitly.


HelloWorld.groovy
class Employee {
 String getName() {return "Krishna"}
 
 void setName() {}

 Integer getId() {return 1234}

 void setId(int id) {}
}

Employee emp1 = new Employee()
println "name : ${emp1.name}, id : ${emp1.id}"

Output
name : Krishna, id : 1234


Previous                                                 Next                                                 Home

No comments:

Post a Comment