Groovy — Classes and named properties
A Groovy class can group named properties with a method that uses them. Store quantity and unit price on one line item and calculate the subtotal from those properties.
A simple example
Read one field
- Start with A point with x = 2
- Do this Read x
- Result 2
class Point { int x }
def point = new Point(x: 2)
println(point.x)
2
Represent an invoice line
Groovy supplies property accessors for the two declared fields. Named property arguments set the values when constructing the instance. subtotal returns its final expression.
A café invoice lists three juices at 125 cents each. Store the quantity and price together, then calculate the subtotal when the receipt is printed. Changing the quantity can then update the total automatically.
Run the example
Groovy 4 on the JVM. Run these commands from the directory containing the example.
groovy Lesson.groovy
class LineItem {
int units
int cents
int subtotal() {
units * cents
}
}
def line = new LineItem(units: 3, cents: 125)
println line.subtotal()
375
The line holds three units at 125 cents each. Multiplication gives 375 cents. Keeping the subtotal derived means there is no third field that can become stale.
Try it yourself
Create a second line with two units at 90 cents each.
Check your answer
Its subtotal is 180 cents. The two subtotals together are 555 cents before any taxes or delivery charges.