Classes, properties and fields
A class in Groovy is a Java class with less typing. A declaration without a modifier is a property: the compiler writes a private field and a public getter and setter for it, so a caller writes book.title and the accessor runs.
A property and its accessors
book.groovy
class Book {
String title
int pages
String describe() {
"${title}, ${pages} pages"
}
}
def book = new Book(title: 'Groovy', pages: 120)
println book.title
println book.pages
println book.describe()
groovy book.groovy
Groovy
120
Groovy, 120 pages
new Book(title: 'Groovy', pages: 120) is the map constructor: it calls the no-arg constructor and then the setters of the named properties. The next lesson takes it apart.
What the compiler wrote
fields.groovy
class Book {
String title
int pages
}
def book = new Book(title: 'Groovy')
println book.getClass().declaredFields*.name.sort()
println book.getClass().declaredMethods*.name.findAll { it.startsWith('get') }.sort()
groovy fields.groovy
[$staticClassInfo, __$stMC, metaClass, pages, title]
[getMetaClass, getPages, getTitle]
The field is private and cannot be reached with book.@title from outside unless the class allows it; the getter is what the property name calls. A declaration with an explicit modifier is a plain field: private int pages gets no accessor, and public int pages would be a public field.
A getter that computes
temperature.groovy
class Temperature {
private double celsius
void setCelsius(double value) {
celsius = value
}
double getCelsius() {
celsius
}
double getFahrenheit() {
celsius * 9 / 5 + 32
}
}
def temperature = new Temperature()
temperature.celsius = 20
println temperature.celsius
println temperature.fahrenheit
groovy temperature.groovy
20.0
68.0
A pair of a setter and a getter is a property with rules: the assignment temperature.celsius = 20 calls setCelsius. A getter with no field behind it is a computed property, and temperature.fahrenheit is the only way a caller sees it.
Related
- Constructors and named parameters: where the map constructor comes from.
- The AST transforms of a data class: the accessors and the rest, written by an annotation.
Автор статьи: Arthur Isaev