问题
I have a groovy superclass that looks like:
class AGroovyClass {
private String str = "hello"
void printString(int nTimes) {
nTimes.times { println str }
}
}
and subclass
class AGroovySubclass extends AGroovyClass {
// some other subclass methods
}
My client code calls:
new AGroovySubclass().printString(5)
And this actually breaks because it says that that there is no such property "str" for AGroovySubclass
I would have thought since the printString method is in AGroovyClass, it should have no problem accessing the "str" property, but clearly I am incorrect. If I wanted to keep "str" private, what is the appropriate way to make this work?
回答1:
It is an old bug with private access modifier. It works if you define str protected. http://jira.codehaus.org/browse/GROOVY-2433
edit: Can you avoid closure, use a for loop instead? Not so cool, but works :)
来源:https://stackoverflow.com/questions/9584957/groovy-subclass-called-superclass-method-that-accesses-closure