tags:

views:

434

answers:

3

What does the 'static' do in this file, sample.groovy?

static class froob {
}

The groovy code compiles fine with 'static' or without it.

+1  A: 

Are you referring to the static class or the static method "main" within the static class?

The keyword "static" means that allocation starts when the program begins and ends when the program ends. In other words, there's no way to programmatically create an instance of class "froob," but rather an instance is automatically create when the program beings and will exist until your program ends.

In the context of your small sample program, it is effectively meaningless. Only the "main" class needs to be static, as it needs to "exist" prior to any code within the program having been executed.

James
Humm. This appears to work/execute from the Groovy Console static class froob { static void main(String[]f){ println "huh" println new froob().class.name } }
Bob Herrmann
Bah! stupid comment formatting<pre>static class froob { static void main(String[]f){ println "huh" println new froob().class.name }}</pre>
Bob Herrmann
+1  A: 

There is absolutely no difference. The static in this situation is ignored.

To test, I created a groovy class and piped the output of "javap -verbose StaticTest" to a file. Then put "static" before the class def and piped that to a 2nd file. I then diffed the two files. The only differences were those unique ids that are associated with the long class ID that gets generated new for every class.

Ted Naleid
A: 

In Java, only an inner class can be static. Prior to Groovy 1.7 inner classes are prohibited, and declaring a top-level class static has no effect.

In Groovy 1.7+ I expect static inner classes to have the same semantics as they do in Java. Declaring a top-level class will likely have no effect (or be prohibited by the compiler).

Don