Using Groovy Classes from Groovy
To use a Groovy class from within our Groovy code, we only have to make sure the Groovy class is in our classpath. We can use the Groovy source code as is, or we can compile it into a .class file and use it—it’s our choice. When our Groovy code references a Groovy class, Groovy looks for the .groovy file with the name of the class in our classpath; if it does not find it, it looks for a .class file with the same name.
Suppose we have Groovy source code Car.groovy, shown here, in a directory named src:
ClassesAndScripts/src/Car.groovy | |
| class Car |
| { |
| int year = 2008 |
| int miles |
| |
| String toString() { "Car: year: $year, miles: $miles" } |
| } |
Also suppose we’re using this class in a file named useCar.groovy ...
Get Programming Groovy 2 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.