Private method in groovy is not private
Asked Answered
C

5

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?

Cramped answered 21/10, 2011 at 16:24 Comment(1)
possible duplicate of What does 'private' mean in Groovy?Checkers
C
24

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

Checkers answered 21/10, 2011 at 16:30 Comment(1)
Incredibly, still unfixed in version 4. issues.apache.org/jira/browse/GROOVY-3010Karilla
I
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

Imine answered 21/10, 2011 at 16:30 Comment(2)
The behavior same in Groovy 2.0 as well.Fae
@kadaj it's now scheduled to be looked at for groovy 3 ;-)Imine
C
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')

    }
}
Crocodilian answered 20/11, 2012 at 9:50 Comment(0)
R
3

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

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

Rangel answered 21/10, 2011 at 16:30 Comment(0)
P
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.

Paresh answered 1/2, 2017 at 2:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.