OOP
OOP in Groovy is implemented in a similar way as in Java. Groovy operates with classes, inheritance and interfaces the similar way. Following subsections describe only some OOP features that are are different in Groovy compared to Java.
Modules are implicitly compiled into classes:
package my.pack // doesn't need to have a specific file location
println this.getClass() // class my.pack.modules
No need for Lombok!
class Animal {
String name // must be declared with no access modifier
float weight
}
def animal = new Animal()
animal.setName("cat")
animal.setWeight(12.7)
println animal.getName() // cat
println animal.getWeight() // 12.7
This is just a very small introduction to traits. For much more details see [groovy_site, 1.4.5. Traits].
trait Flying {
String fly() { "I believe I can fly!" }
}
class Bird implements Flying {}
def b = new Bird()
println b.fly()
// Duck typing
trait SpeakingDuck {
String speak() { quack(3) } // method `quack()` is missing
}
class Duck implements SpeakingDuck {
String methodMissing(String name, args) { // will be called instead of any missing method
println name // quack
println args // [3]
println args[0].getClass() // class java.lang.Integer
return new IntRange(1, args[0] as int).collect {"${name}" }.join(", ")
}
}
def duck = new Duck()
println duck.speak() // quack, quack, quack
Note
Traits also implement the mixin concept. As per the documentation:
@groovy.lang.Mixin
Deprecated. Consider using traits instead.