Adam Pitt
Adam Pitt

Reputation: 128

Java Static Class Variable Initialisation Efficiency

I have the following:

public class ExampleObject extends GridObject { 
  private static Context c; 
  private static final String name = "Example Object"; 
  private static Bitmap skin = BitmapFactory.decodeResource(c.getResources(), R.drawable.defaultObject );
  private static float x,y; 

  public ExampleObject(Context c, float x, float y) { 
    this.c = c; 
    this.x = x; 
    this.y = y; 
  }
}

The class has 3 static class members, The image is a decoded bitmap, I want it to be decoded once and once only for use on ALL instances of this object.

In it's current state is this achieved? or is it decoded every time an instance of this class is created?

How should it be done?

Upvotes: 0

Views: 92

Answers (3)

Thorn G
Thorn G

Reputation: 12766

A static field will only be initialized once; this is guaranteed by the JLS.

However, the decodeResource method will be called when the class is initialized, at which point your Context is null, so it will fail. You'll need something more complex if you want a static field which is only initialized once; something a bit closer to a singleton.

public class ExampleObject extends GridObject { 
  private static final String name = "Example Object"; 
  private static Bitmap skin;
  // = BitmapFactory.decodeResource(c.getResources(), R.drawable.defaultObject );
  private static float x,y; 

  public ExampleObject(Context c, float x, float y) { 
    synchronized(ExampleObject.class) {
      if(skin == null) {
        skin = BitmapFactory.decodeResource(c.getResources(), R.drawable.defaultObject);
      }
    }
    this.x = x; 
    this.y = y; 
  }
}

Upvotes: 2

AADProgramming
AADProgramming

Reputation: 6345

Static variables are initialized only once and A single copy of it is to be shared by all instances of the class.

This single initialization procedure is run automatically, one time only, when the class is first loaded.

You may want to use "static block" to initialize your classes's static fields. For example:

// start of static block 
    static {
        //initialize your static fields
        System.out.println("static block called ");
    }
    // end of static block 

Upvotes: 1

frogatto
frogatto

Reputation: 29285

You can achieve your intended behavior by the following class definition.

public class ExampleObject extends GridObject {
    private static Bitmap skin;

    public static Bitmap getSkin(Context c){
        if(skin == null){
            skin = BitmapFactory.decodeResource( c.getResources(), R.drawable.defaultObject );
        }
        return skin;
    }
}

Upvotes: 1

Related Questions