Initialize member variables in the beginning of class definition or in constructor?
What is the difference between defining and initialising the member variables in the beginning of the class definition,开发者_如何转开发 and defining the member variables first and initialising the member variables in the constructor?
Say, for example:
public class Test {
private int foo = 123;
private boolean flag = false;
public void fooMethod() {...}
}
Versus:
public class Test {
private int foo;
private boolean flag;
public Test() {
foo = 123;
flag = false;
}
public void fooMethod() {...}
}
Thanks in advance.
In your example, the only difference is when they are initialized. According to the JLS, instance variables are initialized before the constructor is called. This can become interesting when you have super classes to deal with, as the initialization order isn't always so obvious. With that, keep in mind "super" instance variables will still be initialized when no explicit super constructor is called.
The difference is the order in which they are initialized / set.
Your class member variables will be declared / set before your constructor is called. My personal preference is to set them in the constructor.
In-class initialization allows you to avoid writing a trivial constructor.
You have to initialize instance members that depend on constructor parameters inside the constructor. It could be reasonable, for readability if nothing else, to put initialization of all other instance members inside the same constructor.
Otherwise, there's no difference.
Initialization when they're declared happens first (and ensures they're always initialized to something). It's typically where you'd put a default value. The constructor happens next, and setting them there allows the caller to specify an initial value with constructor parameters.
public class Test {
private String foo = "default String";
private int bar = 0;
public Test() {
}
public Test(String specificString) {
this.foo = specificString;
}
public void fooMethod() {...}
}
In this example, foo
gets initialized to it's default if you use the empty constructor (or if a subclass doesn't explicitly call its constructor), whereas if you pass a String to the constructor, that overwrites the default value. bar
gets its default, 0, regardless of which constructor is called.
Usually a constructor will accept arguments and assign those arguments to fields of the class.
public Test(int foo, boolean flag)
{
this.foo = foo;
this.flag = flag;
}
精彩评论