Pergunta

Why must a static method, if called in a class definition, be called within a static initializer block unless you are assigning the output to a variable.

public class MyClass {
  int a = staticFunction(); // Allowed.

  static int b = staticFunction(); // Allowed.

  staticFunction(); // Not allowed!

  static  {
    staticFunction(); // Allowed.
  }

  private static int staticFunction() {
    return 1;
  }
}

I am guessing it is because the JVM does not know if this method should be called once when the class is loaded, or every time an object is created.

Foi útil?

Solução 2

It is because the JVM does not know if this method should be called once when the class is loaded (statically), or every time an object is created (per instance).

Therefore, calling this static method must be done in an initializer, be it a static initializer or instance initializer.

Outras dicas

It doesn't have to be called in a static initializer block; it can be called in an instance initializer too, which looks just like a static initializer block but without the word static:

public class MyClass {

  staticFunction(); // Not allowed!

  {
    staticFunction(); // Allowed.
  }

  private static int staticFunction() {
    return 1;
  }
}

The instance initializer is called any time you create a new MyClass object. (It's usually clearer if you put something like that in a constructor, which has about the same effect. But instance initializers can be useful for anonymous classes where you can't write your own constructor.)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top