Skip to content

Classes

Philip Ford edited this page Jan 9, 2017 · 27 revisions

Constructors

  • Can be overloaded.
  • Formal parameters do not need types.
  • Can be called either with positional or named parameters1
    • Moreover, if you do not create a constructor (i.e., you use the default constructor), you always can the default constructor with named parameters, which map instance properties to actual parameters:

      class PersonWOConstructor {                                  
        String name
        Integer age
      }
      
      // The default constructor for the class above can be invoked in any of the following ways:
      def person4 = new PersonWOConstructor()                      
      def person5 = new PersonWOConstructor(name: 'Marie')         
      def person6 = new PersonWOConstructor(age: 1)                
      def person7 = new PersonWOConstructor(name: 'Marie', age: 2)

      This saves you from having to overload the constructor many times to support the different parameter lists.

References

Notes

  1. http://groovy-lang.org/objectorientation.html#_constructors

    In Groovy there are two ways to invoke constructors: with positional parameters or named parameters. The former one is like we invoke Java constructors, while the second way allows one to specify the parameter names when invoking the constructor.

Clone this wiki locally