fweigl
fweigl

Reputation: 22018

Static method without a name

In an Android example class theres this method:

static {        
    addItem(...);
}

When I reference the class, the items are indeed added. I never saw a method like this, a. how is this called and b. I suppose this method is called whenever the class is referenced (or the first time it is referenced)?

Upvotes: 5

Views: 165

Answers (3)

Dariusz
Dariusz

Reputation: 22241

This is not a method. It is a static initializer. It is a way of statically doing some work, on class load, like setting up some data.

Consider this:

static List<String> neverChangingNames;

static {
  neverChangingNames = new ArrayList<String>();
  neverChangingNames.add("Thomas");
  neverChangingNames.add("Derek");
  neverChangingNames.add("Michael");
  neverChangingNames = Collections.unmodifiableList(neverChangingNames);
}

Upvotes: 0

Sanjaya Liyanage
Sanjaya Liyanage

Reputation: 4746

Yes this is Static initialization block and it will be loaded only when class is loading as Fouad said. If you want to perform the functionality inside the Static block when you want you can add a private static method instead. Have a look here

Upvotes: 1

Eng.Fouad
Eng.Fouad

Reputation: 117589

This is called static initializer and the code inside it is invoked only once at class loading.

Upvotes: 9

Related Questions