Lernkurve Lernkurve - 3 months ago 19
Groovy Question

Why can't this top-level Groovy class be static?

Question

Example 1 without the

static
keyword works.

Example 2 with the
static
keyword does not work.

Why can't the top-level class
StaticClass
be
static
? Eclipse says:


Groovy:The class 'StaticClass' has an incorrect modifier static.


The class
StaticInnerClass
can be modified as
static
.

Example 1 works

Start.groovy

assert "static field" == StaticClass.StaticInnerClass.staticField


StaticClass.groovy

class StaticClass { // Just "class", no "static" modifier
static class StaticInnerClass {
static String staticField = "static field"
}
}


Example 2 does not work

Start.groovy

assert "static field" == StaticClass.StaticInnerClass.staticField


StaticClass.groovy

static class StaticClass { // Modifier "static" does not work
static class StaticInnerClass {
static String staticField = "static field"
}
}


Possibly related question

groovy static class

Versions


  • Eclipse 3.8.1

  • Groovy-Eclipse plugin 2.8.0


Answer

Only nested classes can be static (just like in Java).

If you just don't want your class to be instantiable, you can qualify the individual definitions in a class with the static keyword, e.g.:

class MyClass {

  static public count = 1

  static incr() {
    count = count + 23
  }
}