class RectConstructor{
double length;
double width;
double area(){
return length*width;
}
RectConstructor(double width,double length){//带参数的构造方法
this.length=length; //this指调用本类的其他构造方法,this必须为第一条语句。
this.width=width;
}
}
public class RectDemo{
public static void main(String args[]) {
RectConstructor rect1=new RectConstructor(10,20);
RectConstructor rect2=new RectConstructor(3,6);
double ar;
ar=rect1.area();
System.out.println("第一个长方形的面积是"+ar);
ar=rect2.area();
System.out.println("第二个长方形的面积是"+ar);
}
}
控制台输出结果为:
第一个长方形的面积是200
第二个长方形的面积是18
this用法总结:
第一、通过this调用另一个构造方法,用发是this(参数列表),这个仅仅在类的构造方法中,别的地方不能这么用。