When you try to access a field in Groovy, it calls the
getter method implicitly. When you try to set a value to the variable, it calls
the setter method implicitly.
HelloWorld.groovy
class Employee{ String firstName String lastName String getFirstName(){ println "Getting the firstName" return firstName } String getLastName(){ println "Getting the lastName" return lastName } String setFirstName(String firstName){ println "Setting the firstName" this.firstName = firstName } String setLastName(String lastName){ println "Setting the firstName" this.lastName = lastName } } Employee emp = new Employee() emp.firstName = "krishna" emp.lastName = "Gurram" printEmployeeDetails(emp) void printEmployeeDetails(Employee employee){ println "*******************************" String firstName = employee.firstName String lastName = employee.lastName println "[${firstName}, ${lastName}]" println "*******************************" }
Output
Setting the firstName Setting the firstName ******************************* Getting the firstName Getting the lastName [krishna, Gurram] *******************************
By using Direct field access operator (.@), you can
access the property without calling getter and setter methods.
HelloWorld.groovy
class Employee{ String firstName String lastName String getFirstName(){ println "Getting the firstName" return firstName } String getLastName(){ println "Getting the lastName" return lastName } String setFirstName(String firstName){ println "Setting the firstName" this.firstName = firstName } String setLastName(String lastName){ println "Setting the firstName" this.lastName = lastName } } Employee emp = new Employee() emp.@firstName = "krishna" emp.@lastName = "Gurram" printEmployeeDetails(emp) void printEmployeeDetails(Employee employee){ println "*******************************" String firstName = employee.@firstName String lastName = employee.@lastName println "[${firstName}, ${lastName}]" println "*******************************" }
Output
******************************* [krishna, Gurram] *******************************
No comments:
Post a Comment