What is Instance Initializer in Java?

本文通过一个实例详细介绍了Java中实例变量初始化器、实例初始化器和静态初始化器的执行顺序及工作原理,并探讨了实例初始化器的使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In this post, I will first use an example to show what are instance variable initializer, instance initializer and static initializer, and then illustrate how the instance initializer works in Java.

1. Execution Order

Look at the following class, do you know which one gets executed first?

public class Foo {
 
//instance variable initializer
String s = "abc";
 
//constructor
public Foo() {
System.out.println("constructor called");
}
 
//static initializer
static {
System.out.println("static initializer called");
}
 
//instance initializer
{
System.out.println("instance initializer called");
}
 
public static void main(String[] args) {
new Foo();
new Foo();
}
}

Output:

static initializer called
instance initializer called
constructor called
instance initializer called
constructor called

2. How does Java instance initializer work?

The instance initializer above contains a println statement. To understand how it works, we can treat it as a variable assignment statement, e.g., b = 0. This can make it more obvious to understand.

Instead of

int b = 0

, you could write

int b;
b = 0;

Therefore, instance initializers and instance variable initializers are pretty much the same.

3. When are instance initializers useful?

The use of instance initializers are rare, but still it can be a useful alternative to instance variable initializers if:

(1) initializer code must handle exceptions
(2) perform calculations that can't be expressed with an instance variable initializer.

Of course, such code could be written in constructors. But if a class had multiple constructors, you would have to repeat the code in each constructor.

With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. (I guess this is just a concept, and it is not used often.)

Another case in which instance initializers are useful is anonymous inner classes, which can't declare any constructors at all. (Will this be a good place to place a logging function?)

Thanks to Heinrich Hartmann for his comment:

Also note that Anonymous classes that implement interfaces [1] have no constructors. Therefore instance initializers are neede to execute any kinds of expressions at construction time.

Reference:
Object initialization in Java


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值