构造器里面调用其它构造器,格式方法如下:
1、使用this调用另一个重载构造器,只能在构造器中使用;
2、必须写在构造器执行体的第一行语句;
示例如下:
import static java.lang.System.*;//-导入java.lang.System下全部的静态成员变量--减少代码书写量
public class Constructor{
//-定义4个实例变量
public String name;
public String color;
public double weight;
public int age;
public static void main(String[] args){
Constructor C=new Constructor("张三","蓝色",65.5,26);
out.println(C.name);
out.println(C.color);
out.println(C.weight);
out.println(C.age);
}
//-创建一个空的构造器
public Constructor(){
}
//-创建一个包含2个参数的构造器--构造器重载
public Constructor(String name,String color){
//-部分实例变量赋值
this.name=name;
this.color=color;
}
//-创建一个包含4个参数的构造器--构造器重载
public Constructor(String name,String color,double weight,int age){
//-构造器里面调用其它构造器,格式方法如下:
//-1、使用this调用另一个重载构造器,只能在构造器中使用;
//-2、必须写在构造器执行体的第一行语句;
this(name,color);
this.weight=weight;
this.age=age;
}
}
执行结果如下: