- 指定初始化
如果想爲某個變量賦初始值,有一種很直接的辦法,就是在定義類成員變量的地方爲其賦值(在C++裏不能這樣做,儘管C++的新手們總想這樣做)。以下代碼片段直接給成員變量賦初值。
public class InitialValues {
boolean bool = false;
char ch = 'x';
int i = 939;//....
}
也可以用同樣的方法初始化非基本類型的對象。如果Depth是一個類
class Depth{}
public class Measurement {
Depth d = new Depth();
//....
}
甚至可以通過調用某個方法來提供初值:
public class MethodInit {
int i = f();
int f() {return 11;}
}
這個方法也可以帶有參數,但這些參數必須是已經被初始化了的。
public class MethodInit2 {
int i = f();
int j = g(i);
int f() { return 11; }
int g int(int n) { return n * 10; }
- 構造器初始化