Getting Groovy, Part III

Written By: James Williams

- 22 Aug 2006 -
















Description: This tutorial is the third part of a series introducing the major features of Groovy, a dynamic scripting language for the Java Virtual Machine. We will be covering annotations, XML files, and file input/output.

  1. Annotation & Overloaded Constructors
  2. XML Files
  3. Files

The annotation

In traditional object-oriented languages, a good portion of any class definition is spent writing getters and setters...until now. The annotation, when applied to a variable, automatically creates a public getter and setter behind the scenes to access the variable. It can accompany a type definition or appear alone. Below is a simple GradeReport class using properties:

public class GradeReport {
        @Property name
        @Property subject
        @Property String grade
}

We can assign values like a normal class variable or by using the getXXX pattern:

mathGrade.name = "John"
mathGrade.setSubject("Math")
mathGrade.grade = "A-"

Returning values can be done the same way:

println mathGrade.name                        // returns "John"
println mathGrade.getGrade()                // returns "A-" 

Overloaded constructors

There is really no need for multiple class constructors in Groovy. If we want to declare values in our constructor, we list the properties(or public variables) and their values, separated by colons(like a hash map)

artGrade = new GradeReport(name:'Kristen', subject:'Art', grade:'B+')

Using the above statement is the same as calling a no parameter GradeReport constructor and calling the setters for the name, subject, and grade. If we want a specific constructor that will not share code with the other constructors, we can declare it like a normal overloaded constructor.

Next >>