Reputation: 3733
I am trying to understand the below point in the codehaus page under 'Properties and field rules' section.
Does that mean we could have two variables one private and other public and the private uses the public field? Please see below sample program I tried for my understanding.
class Car {
private def brake
def brake // when does this get used? if I declare public, it gives compilation error
protected void setBrake() {
this.brake = brake
}
static def main(args) {
Car c = new Car()
c.setBrake 'abc'
println c.brake
}
}
Upvotes: 2
Views: 284
Reputation: 50275
This is what it means.
class Car {
private def brake
// Same name property will add getter/setter for the above field
def brake
static def main(args) {
Car c = new Car()
c.setBrake 'abc' // Use setter
println c.getBrake() // Use getter
}
}
Try above sample commenting out the property, you should see groovy.lang.MissingMethodException
for setBrake()
, because it gets added by the property.
The verbiage in the page says that if you have a field (may be private) and a property ( def brake) then the property will add the accessor methods for that field instead of creating a new private field.
Upvotes: 3