标题: 为什么使用有餐宿的构造方法就可以实现,而使用无参数的.... [打印本页] 作者: 愿随风丶飘雪 时间: 2015-12-30 22:45 标题: 为什么使用有餐宿的构造方法就可以实现,而使用无参数的.... public class Rectangle {
public static void main(String[] args) {
Rectangle1 r = new Rectangle1();
r.setWidth(10);
r.setWidth(20);
int length=2*(r.getWidth()+r.getHigh());//使用无参数的构造方法实现
int area=r.getWidth()*r.getHigh();
System.out.println("周长是"+length); //结果是40
System.out.println("面积是"+area); //结果是0 不正常
/*System.out.println("周长是"+r.getLength());//结果是40
System.out.println("面积是"+r.getArea());*/ //结果是0
Rectangle1 r2 = new Rectangle1(30,40);//使用有参数的构造该方法实现
System.out.println("周长是"+r2.getLength()); //结果是140
System.out.println("面积是"+r2.getArea()); //结果是1200
}
}
class Rectangle1{
int width;
int high;
public Rectangle1(){}
public void setWidth(int width){
this.width=width;
}
public int getWidth(){
return width;
}
public void setHigh(int high){
this.high=high;
}
public int getHigh(){
return high;
}
public Rectangle1(int width,int high){
this.width=width;
this.high=high;
}
public int getLength(){
return 2*(width+high);
}
public int getArea(){
return width*high;
}
}作者: 愿随风丶飘雪 时间: 2015-12-30 22:47
求矩形的面积,为什么无参数的构造方法就不行呢?求大神指导一下作者: iori 时间: 2016-1-1 17:35
public class Rectangle {
public static void main(String[] args) {
Rectangle1 r = new Rectangle1();
r.setWidth(10);
r.setWidth(20);
亲,我真心不想多说什么。编程是个仔细活。你看一下你的程序第三行,和第四行有什么区别吗?
r.setWidth(10);
r.setWidth(20);
你能告诉我你给high赋值了吗?