25
class A {
    private def sayHello() {
       println "Anish"
    } 
 }

 def a_obj = new A()
 a_obj.sayHello()

output : Anish

Is there any way to protect sayHello() in groovy or am I missing something?

alayor
  • 4,537
  • 6
  • 27
  • 47
anish
  • 6,884
  • 13
  • 74
  • 140
  • 2
    possible duplicate of [What does 'private' mean in Groovy?](http://stackoverflow.com/questions/4005700/what-does-private-mean-in-groovy) – Andrey Adamovich Oct 21 '11 at 16:34

5 Answers5

24

There is defect on that in Groovy issue tracking system and that defect is still open.

mkobit
  • 43,979
  • 12
  • 156
  • 150
Andrey Adamovich
  • 20,285
  • 14
  • 94
  • 132
  • 1
    Incredibly, still unfixed in version 4. https://issues.apache.org/jira/browse/GROOVY-3010 – Blaine Jun 04 '22 at 13:14
10

Searching for [groovy] private reveals:

groovy call private method in Java super class

What does 'private' mean in Groovy?

How to define private getter method in Groovy Bean?

It's not clear if it is a bug or by design, but it is going to get looked at again in Groovy 2.0

Community
  • 1
  • 1
tim_yates
  • 167,322
  • 27
  • 342
  • 338
6

You can use closures to achieve a similar effect, basically the same way you would do information hiding with Javascript.

package test

class FunctionTests {

    def privilagedObj = {

        def privVar = 'foo'

        def privateFunc = { x -> println "${privVar} ${x}"}

        return {x -> privateFunc(x) } 
    }

    public static void main(String[] args) {

        def test = new FunctionTests().privilagedObj()

        test('bar')

    }
}
mkobit
  • 43,979
  • 12
  • 156
  • 150
Jason
  • 406
  • 1
  • 5
  • 16
3

I think its a bug in groovy that is fixed in groovy++.

https://issues.apache.org/jira/browse/GROOVY-1875

Ilya Serbis
  • 21,149
  • 6
  • 87
  • 74
hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
1

As other posts have mentioned, this may be a bug in Groovy. I've been sticking to a simple convention of prefixing private member names with a leading underscore (similar to Python) to denote that it's private which helps me understand from a client side perspective what I should be calling.

solstice333
  • 3,399
  • 1
  • 31
  • 28