class Vchicle
{
int passengers;
double weight;
String color;
Vchicle(int p,double w)
{
this(p,w,"WHITE"); //调用另一个构造函数
}
Vchicle(int p,double w,String c)
{
this.passengers=p;
this.weight=w;
this.color=c;
}
/**void setData(int passengers,double weight,String color)
{
this.passengers=passengers;
this.weight=weight;
this.color=color;
}*/
void outputVariables()
{
System.out.println(passengers+" "+weight+" "+color);
}
}public class ThisDemo
{
public static void main(String args[])
{
Vchicle v1=new Vchicle(3,5.5,"WHITE");
v1.outputVariables();
Vchicle v2=new Vchicle(3,5.0);
v2.outputVariables();
}
}
{
int passengers;
double weight;
String color;
Vchicle(int p,double w)
{
this(p,w,"WHITE"); //调用另一个构造函数
}
Vchicle(int p,double w,String c)
{
this.passengers=p;
this.weight=w;
this.color=c;
}
/**void setData(int passengers,double weight,String color)
{
this.passengers=passengers;
this.weight=weight;
this.color=color;
}*/
void outputVariables()
{
System.out.println(passengers+" "+weight+" "+color);
}
}public class ThisDemo
{
public static void main(String args[])
{
Vchicle v1=new Vchicle(3,5.5,"WHITE");
v1.outputVariables();
Vchicle v2=new Vchicle(3,5.0);
v2.outputVariables();
}
}
没有注释的是这个类的有参构造函数,被注释掉的方法只是一个与这个有参构造函数实现相同功能的方法。
当你用这个有参构造函数时可以直接写成Vchicle v1=new Vchicle(3,5.5,"WHITE");而当你调用被注释掉的方法时需要写成Vchicle vl=new Vchicle();
vl.setData(3,5.5,"WHITE");
哪个更方便呢?