zeroin23
zeroin23

Reputation: 1821

java nested class with static initializer

Was reading the book called Emergent Design and on the topic of singleton ...

public class MyApp {
 private class SingletonHolder {
  public Object singleton; 
  static {
   singleton = new Object(); 
  }
 }
}

then eclipse keeps complaining about the static {}

Was reading Java, classes supposed to be able to have multi static initializer. So how can I make the above work ?


/tmp/jc_4873/MyApp.java:5: non-static variable singleton cannot be referenced from a static context
   singleton = new Object(); 
   ^
/tmp/jc_4873/MyApp.java:4: inner classes cannot have static declarations
  static {
  ^
2 errors

public class MyApp {
 private class SingletonHolder {
  public static Object singleton; 
  static {
   singleton = new Object(); 
  }
 }
}

/tmp/jc_8488/MyApp.java:3: inner classes cannot have static declarations
  public static Object singleton; 
                       ^
/tmp/jc_8488/MyApp.java:4: inner classes cannot have static declarations
  static {
  ^
2 errors

public class MyApp {
 private static class SingletonHolder {
  public static Object singleton; 
  static {
   singleton = new Object(); 
  }
 }
}

Upvotes: 1

Views: 1576

Answers (2)

akf
akf

Reputation: 39485

For a field to be legally referenced in a static context, the field must either be local to the context or declared as static within the class. If you want to reference singleton, you will need to declare it static.

Upvotes: 6

fastcodejava
fastcodejava

Reputation: 41077

You need to put private static Object singleton; Static block cannot modify a non static variable.

Upvotes: 2

Related Questions