3

So I did read the tread of what and when static initalizer is executed from this thread. Static initializer in Java. But I am running into some old code written by someone else and can't seem to understand why he would use it the way he did.

My Class:

public class ClassA extends Thread {
  .... private vars ....

  private static Config config;

  static {
    config = null;
  }

  public ClassA(Config config) {
    ClassA.config = config;
  }
}

Why didn't he just do this?

public class ClassA extends Thread {
  .... private vars ....

  private static Config config = null;

  public ClassA(Config config) {
    ClassA.config = config;
  }
}

I understand that static initalizer gets call as the class being redenered, so it sets config => null, while if i don't use static initalizer, instance variables get initalizer right before the constructor, and right after super. So wouldn't the two class be doing the same thing?

Community
  • 1
  • 1
Churk
  • 4,556
  • 5
  • 22
  • 37

5 Answers5

5

These classes are doing the same thing, but more complex static initializers can't always be done on a single line.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • So it is safe to say that I can use the second implementation and would not change any functionality. – Churk Apr 17 '12 at 15:21
  • Maybe the author of the class did some more complex initialization first and removed it then without removing the static initializer. But it's just a guess. Anyway, your answer is precise and correct (+1). – Michael Schmeißer Apr 17 '12 at 15:21
  • @Churk In this particular case? Yes. – Louis Wasserman Apr 17 '12 at 15:21
  • @MichaelSchmeißer, thank you, and I just looked at the source versioning, and yes, this static initalizer was more complex which explains why it was there. – Churk Apr 17 '12 at 15:23
3

The static initializer in your first example won't have any effect on the behavior of that class. You could remove it entirely and nothing would change.

Mike Deck
  • 18,045
  • 16
  • 68
  • 92
1

Why did I write x = x + 1 instead of x++ ? No particular reason, I just did it that way. I think it's the same here, because the 2 are basically identical and it doesn't really matter. On the other hand, if more complicated initialization is desired sometime in the future, maybe he can't do that in that single line of code.

Radu Murzea
  • 10,724
  • 10
  • 47
  • 69
0

The static block will initialize config only once when class is loaded, no matter how many instances of ClassA there are.

It doesn't matter which solution, it's just a technicality, I've seen people use both.

Charles Menguy
  • 40,830
  • 17
  • 95
  • 117
0

Both are doing exactly the same thing, It a matter of design choice.

Bitmap
  • 12,402
  • 16
  • 64
  • 91