你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