Classes are defined in Groovy similarly to Java. Methods can be class (static) or instance based and can be public, protected, private and support all the usual Java modifiers like synchronized.
One difference with Groovy is that by default things are public unless you specify otherwise.
Groovy also merges the idea of fields and properties together to make code simpler, please refer to the Groovy Beans section for details of how they work.
Each class in Groovy is a Java class at the bytecode / JVM level. Any methods declared will be available to Java and vice versa. You can specify the types of parameters or return types on methods so that they work nicely in normal Java code. Also you can implement interfaces or overload Java methods using this approach.
If you omit the types of any methods or properties they will default to java.lang.Object at the bytecode/JVM level.
You can also use another class implemented in Groovy. e.g.
Make sure the classpath is OK.
Groovy supports plain scripts, which do not have a class declaration. Here's the hello world script
If you compile the above script to bytecode using groovyc, you get a single class named after the name of the script. e.g. if this was saved in Foo.script you'd get a Foo.class file.
You can run this Java code on the command line (assuming you're classpath has groovy.jar and asm.jar).
This will execute the autogenerated main(String args) method in the bytecode which instantiates the Foo class, which extends the
There's no need to use a Binding if you don't want to; Foo will have a no-argument constructor as well. Though using a Binding you can easily pass in variables. After the end of the script any variables created will be in the Binding for you to access in Java.
Scripts and functions
If you just want to write some simple scripts and need some simple functions you can declare functions without writing a class.
One difference from normal class-based groovy is that the def keyword is required to define a function outside of a class.
Here's an example of a simple script with a function. Note that if ever you need things like static or instance variables and so forth then maybe its time to actually write a class