Groovy subclass called superclass method that acce

2019-02-25 12:41发布

问题:

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 :)