blog rss feed

Getting groovy - an introduction to the Groovy language

Keywords:

Last editor: Dave Cherry, last modified: Aug 22, 2009

Groovy has different visibility rules to Java. Any field that's declared without a modifier is actually treated as a private field with auto generated getter and setter methods. This provides a very quick means of implementing java beans. For example:

// create an instance of the class declared below def myObj = new SomeGroovyClass(name: 'Dave', address: 'Some address, somewhere')  // we are going to introduce string expressions in the next page, // this prints the name and address properties println "myObj's details = ${myObj.name}, ${myObj.address}"  // call a method myObj.doSomething()  // simple class with two java beans and a method class SomeGroovyClass {     String name     String address      void doSomething() {         println "Hello"         } } 

First, you've probably noticed I have not put a semicolon after each statement - (I did this on purpose to highlight its not required). Be assured this code will still compile. Groovy also supports named parameters, notice how we construct the instance of SomeGroovyClass.

Both name and address will be declared private with public java bean accessor methods automatically generated, this is true whenever a variable is declared without a scope modifier. To prevent this declare the variable private. Methods declared without a scope are automatically made public. Any java bean properties on a class can be access by the property name, for example assume in the following example obj has two methods getStyle and setStyle:

String style = obj.style
obj.style = newStyle;

I hope this has introduced you to a few of the concepts, next we move on to Strings, Collections and closures.

<< 1 2 3 4 >>

Please leave a comment



Search

Blog calendar

blog: previous month September 2010 blog: next month
su mo tu we th fr sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30