Sunday 27 January 2019

Groovy: Constructor invocation


There are four ways to invoke the constructor.
a.   Normal Java way using new operator
b.   Using coercion with as keyword
c.    Using coercion in assignment
d.   Using named parameters

For example, take below Employee class, I defined one constructor that takes employee name and id as arguments.

class Employee{
         String name
         int id

         Employee(name, id){
                  this.name = name
                  this.id = id
         }
        
}

Using new operator
Employee emp1 = new Employee("Krishna", 123)

Using coercion with as keyword
Employee emp2 = ["Krishna", 123] as Employee

Using coercion in assignment
Employee emp3 = ["Krishna", 123]

Find the below working application.

HelloWorld.groovy
class Employee{
 String name
 int id

 Employee(name, id){
  this.name = name
  this.id = id
 }
 
}

Employee emp1 = new Employee("Krishna", 123)
Employee emp2 = ["Krishna", 123] as Employee
Employee emp3 = ["Krishna", 123]

void printEmployee(Employee emp){
 println "name: ${emp.name}, id: ${emp.id}"
}

printEmployee(emp1)
printEmployee(emp2)
printEmployee(emp3)

Output
name: Krishna, id: 123
name: Krishna, id: 123
name: Krishna, id: 123

Using named parameters
If a class has default constructor, then you can create objects by passing parameters in the form of a map (property/value pairs)


HelloWorld.groovy
class Employee{
 String name
 int id
}

Employee emp1 = new Employee(name : "Krishna", id : 123)
Employee emp2 = new Employee(name : "Krishna")
Employee emp3 = new Employee()


void printEmployee(Employee emp){
 println "name: ${emp.name}, id: ${emp.id}"
}

printEmployee(emp1)
printEmployee(emp2)
printEmployee(emp3)

Output
name: Krishna, id: 123
name: Krishna, id: 0
name: null, id: 0



Previous                                                 Next                                                 Home

No comments:

Post a Comment