你constuctor必須像聲明任何其他方法(但它被稱爲相同,類名,並且不提供任何返程):
public class ConstructorExample {
//this is your class fieald
private double x,y;
//here is the constructor
public ConstructorExample(int x,int y){
//set the class field's values, via this (means class),
//because the arg names is the same as fields names
this.x = x;
this.y = y;
}
public static void main(String[] args) {
//here is how you can create a class instance inside the main method
ConstructorExample example = new ConstructorExample(1,1);
}
}
此外,如果你有沒有定義任何構造函數,java會添加默認的,沒有參數。因此,它可能看起來像:
public class ConstructorExample {
public static void main(String[] args) {
//here is how you can create a class instance inside the main method
//with the default constructor
ConstructorExample example = new ConstructorExample();
}
}
如果你有多個構造函數,那麼你可以再次調用通過this
一個從其他,如:
public class ConstructorExample {
//this is your class fieald
private double x,y;
//here is the constructor with the single argument
public ConstructorExample(int x){
this.x = x;
}
//here is the constructor with 2 arguments
public ConstructorExample(int x,int y){
//you can call another constructor with the arguments
this(x);
this.y = y;
}
public static void main(String[] args) {
//here is how you can create a class instance inside the main method
ConstructorExample example = new ConstructorExample(1,1);
}
}
'ConstructorExample'不繼承默認的構造函數,因爲它有一個參數。 – Stanislav