Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy equivalent to java's declaration without access modifier

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?

like image 578
Ricardo Mogg Avatar asked Jun 04 '14 17:06

Ricardo Mogg


People also ask

How can you access the class if it is declared without any access modifiers?

A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

How do I declare a variable in Groovy?

Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.

What happens if you don't declare access modifiers?

default: It is also referred to as no modifier. Whenever we do not use any access modifier it is treated as default where this allows us to access within a class, within a subclass, and also non-sun class within a package but when the package differs now be it a subclass or non-class we are not able to access.

Can I write methods without access modifier and modifier?

Default: When no access modifier is specified for a class, method, or data member – It is said to be having the default access modifier by default. The data members, class or methods which are not declared using any access modifiers i.e. having default access modifier are accessible only within the same package.


1 Answers

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.

like image 180
Cᴏʀʏ Avatar answered Oct 12 '22 15:10

Cᴏʀʏ