Lets see a small snippet of java code
class Foo {
int i = 0;
int j;
public Foo(int j){
this.j = j;
}
}
Above example shows two ways of initializing variables in Java. But my question is which variable first get initialized? The variable outside the constructor or the variable inside the constructor? When I instantiate the above class Foo foo = new Foo(5)
, I know that the constructor of the class get called which implies variable j
get initialized first. Can anyone make me clear about the ordering.
In your case the int j
happens first and defaults to 0
, then gets reassigned to 5
when the constructor is called on to create a new instance.
j
only gets re-assigned when the constructor runs. Instance members get initialized first when you assign them something outside the constructor.
Each line of code gets executed in the order it appears. The declarations happen before the constructor always, in the order they are listed in the code.
You should only initialize instance members in a single place, inside a single constructor.
Relying on defaults leads to hard to track down bugs, and makes testing a nightmare, but a instance member that is unassigned will stand out like a sore thumb to the IDE, the compiler and at runtime. Unfortunately for primitives like int
they default to 0
which might not be what you want/need.
A better design is:
private final int j;
public Foo(final int j) { this.j = j; }
This keeps the j
from getting assigned anything on initialization and you never have to worry about it changing.
Let's say you have this class
public class Test
{
int i = 4;
public Test()
{
System.out.println(i);
}
}
When you create an instance of Test
, the output will be 4
. This means that the initialization goes first. Then the constructor is called. Because if the constructor were first and the initialization of i
second, you won't get 4
as output.
int i = 0;
i is an instance variable and hence will get default value which is 0. So you don't need to assign 0 to it explicitly.
Coming to your question
But my question is which variable first get initialized?
Then the answer would be i is initialized before j. Because if you see byte codes of your snippet Object is created first which will initialize your instance variables and then constructor is called.
When ever you create Object creation, First declaration of variable are being done.After that only variables are defined. In your case first "j" variable will declared first ie class variable.After that the value will be assigned to "j" in constructor of a class.
Ordering :-
for your question I think i
and j
will be initailized together as i=0
; and j
as 0 (with int
default value.)
Because in constructor you are just changing the value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.