开发者

Some questions regarding Initialization Block in Java

开发者 https://www.devze.com 2022-12-27 19:50 出处:网络
Where have you mostly used the initialization block? Can you use these to assign values to static instance variables?
  1. Where have you mostly used the initialization block?
  2. Can you use these to assign values to static instance variables?
  3. How is this different from assigning using a constructor?
  4. My book says that the initialization block is executed when the "class is loaded". What does loading a class mean?

Additional Question Which is better?

class {static final instance-variable = val} 

or

开发者_如何学运维
class {static final instance-variable;  static {instance-variable=val}}


An initialization block is always called regardless of the constructor you'd like to use. So, if the class in question has more than one constructor and you'd like to run some code regardless of the constructor used, then use an initialization block.

However, when used to assign default values, I'd just assign them directly. If they are even constants, then I'd add final to the list of modifiers as well.

private static final String VAL1 = "VALUE";

Update since you drastically changed the question, here's a renewed answer:

1) Where have you mostly used the initialization block?

To execute some code regardless of the constructor used.

2) Can you use these to assign values to static instance variables?

You'll need a static initializer block.

private static final String FOO;

static {
    FOO = "bar";
}

This has the benefit that you can do more than just assigning a value. E.g. getting it from some method and handling the exception:

static {
    try {
        FOO = getItSomehow();
    } catch (Exception e) {
        throw new ExceptionInInitializerError(e);
    }
}

3) How is this different from assigning using a constructor?

It's always assigned regardless of the constructor used.

4) My book says that the initialization block is executed when the "class is loaded". What does loading a class mean?

The book is actually talking about a static initialization block. A class is usually loaded when you reference it for the first time in your code. You can also forcibly load it by Class#forName() (such as you do with JDBC drivers). I've posted an answer with more examples and explanation before here.

Hope this helps.


Additional Question Which is better?

class {static final instance-variable = val} 

or

class {static final instance-variable;  static {instance-variable=val}}

They have identical behaviour. In this case, the first form is better since it is less verbose and clearly more easy to read.

Only use a static initializer block if the initialization is too complicated to be expressed clearly using a series of static declarations with initializer expressions.

0

精彩评论

暂无评论...
验证码 换一张
取 消