Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java static initializer seems to be redundant

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?

like image 861
Churk Avatar asked Aug 10 '26 05:08

Churk


1 Answers

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

like image 155
Louis Wasserman Avatar answered Aug 12 '26 10:08

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!