When I define a Java class:
class A {
private String str = "init method 1";
public A() {
str = "init method 2";
}
}
I can either init str
when define it or init it in constructor. My question is what difference of the two methods is? Which method is preferred?
The initialization block values are assigned before constructor assigns them.
So the value init member 1
will be assigned first and then init member 2
will be assigned.
Consider this example from theJavaGeek
class InitBlocksDemo {
private String name ;
InitBlocksDemo(int x) {
System.out.println("In 1 argument constructor, name = " + this.name);
}
InitBlocksDemo() {
name = "prasad";
System.out.println("In no argument constructor, name = " + this.name);
}
/* First static initialization block */
static {
System.out.println("In first static init block ");
}
/* First instance initialization block */
{
System.out.println("In first instance init block, name = " + this.name);
}
/* Second instance initialization block */
{
System.out.println("In second instance init block, name = " + this.name);
}
/* Second static initialization block */
static {
System.out.println("In second static int block ");
}
public static void main(String args[]) {
new InitBlocksDemo();
new InitBlocksDemo();
new InitBlocksDemo(7);
}
}
This outputs,
In first static init block
In second static int block
In first instance init block, name = null
In second instance init block, name = null
In no argument constructor, name = prasad
In first instance init block, name = null
In second instance init block, name = null
In no argument constructor, name = prasad
In first instance init block, name = null
In second instance init block, name = null
In 1 argument constructor, name = null
The program flows as follows.
InitBlocksDemo
is loaded into JVM.main
method is encountered.new InitBlocksDemo();
causes the no-argument constructor to be invoked.super
no-argument constructor, control goes to super class i.e. Object
classnull
.null
new InitBlocksDemo(7);
causes the one-argument constructor to be invoked. Rest of the process is same. Only difference is that name is not re-assigned a new value hence it will print null
There is no difference between them, the compiler copies the initialization blocks to the constructors
If you, decompile the generated class file for the class
class A {
private String str1 = "init method 1";
private String str2;
public A() {
str2 = "init method 2";
}
public A(String str2) {
str2 = str2;
}
}
you can find
class A
{
private String str1;
private String str2;
public A()
{
str1 = "init method 1";
str2 = "init method 2";
}
public A(String str2)
{
str1 = "init method 1";
str2 = str2;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With