Groovy subclass called superclass method that accesses closure

ⅰ亾dé卋堺 提交于 2019-12-20 02:24:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!