8

So, I can declare a class in Groovy as:

//groovy-code
class Person {

}

which is the equivalent to write in java something like:

//java-code
public class Person {

}

Just out of curiosity.. what's groovy equivalent to this coded in java:

//java-code
class Person {

}

I mean is there a way to achieve the same that I can achieve in Java by declaring something without an access modifier?

Ricardo Mogg
  • 589
  • 6
  • 18

1 Answers1

12

Since the default access modifier for a class in Java is "package-private", I think the closest you could get in Groovy to the same behavior would be to make the class "package-protected," which is done with the @PackageScope annotation:

@PackageScope class Person {

}

By the way, there's an open and unresolved bug (feature?) in Groovy that prevents any sort of "private" visibility from working. Implementation is planned for Groovy v3.0.

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • So that one is close. But does this mean that if I want to use a Java class without access modifiers in groovy, I can't? or how will it be treated by groovy? – Ricardo Mogg Jun 04 '14 at 18:01
  • 1
    You can, but it will be treated as `public` when compiled. – Cᴏʀʏ Jun 04 '14 at 18:04
  • "But does this mean that if I want to use a Java class without access modifiers in groovy, I can't?". No. You use Java classes without access modifiers from Groovy in exactly the same way you would use them from Java. The syntax is no different. The PackageScope annotation only relates to defining classes, not using other classes. – Jeff Scott Brown Jun 05 '14 at 05:15
  • For private fields/methods, see also: https://stackoverflow.com/questions/7852370/private-method-in-groovy-is-not-private It seems the linked jira ticket is now https://issues.apache.org/jira/browse/GROOVY-7246 – Kosi Aug 06 '18 at 19:28