1、题目
定义长方形类,含:属性:宽、高(整型);
构造方法3个:(1)无参——宽、高默认值为1;(2)1个参数——宽、高相等;(3)2个参数——宽、高各为参数值。
方法:求周长、面积;
要求:进行测试计算周长和面积。
2、代码
package com.situ.day6;
//2、定义长方形类,含:
// 属性:宽、高(整型);
// 构造方法3个:(1)无参——宽、高默认值为1;(2)1个参数——宽、高相等;(3)2个参数——宽、高各为参数值。
// 方法:求周长、面积;
// 要求:进行测试计算周长和面积。
public class Rectangle {
private int width;
private int height;
public Rectangle() { //无参构造方法设置默认值
this.width = 1;
this.height = 1;
}
public Rectangle (int width) { //一个参数
this.width = width;
height = width; //宽高相等
}
public Rectangle (int width, int height) { //两个参数
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
//方法
//求周长
public int getPerimeter(int width, int height) {
return width * 2 + height * 2;
}
//求面积
public int getArea(int width, int height) {
return width * height;
}
public static void main(String[] args) {
int width = 0;
int height = 0;
//调用无参构造方法构造长方形对象
Rectangle rectangle1 = new Rectangle();
width = rectangle1.getWidth();
height = rectangle1.getHeight();
System.out.println("调用无参构造方法时:");
System.out.println("周长为:" + rectangle1.getPerimeter(width, height));
System.out.println("面积为:" + rectangle1.getArea(width, height));
//调用一个参数的构造方法时
Rectangle rectangle2 = new Rectangle(2);
width = rectangle2.getWidth();
height = rectangle2.getHeight();
System.out.println("调用一个参数的构造方法时:");
System.out.println("周长为:" + rectangle2.getPerimeter(width, height));
System.out.println("面积为:" + rectangle2.getArea(width, height));
//调用两个参数的构造方法时
Rectangle rectangle3 = new Rectangle(2, 3);
width = rectangle3.getWidth();
height = rectangle3.getHeight();
System.out.println("调用两个参数的构造方法时:");
System.out.println("周长为:" + rectangle3.getPerimeter(width, height));
System.out.println("面积为:" + rectangle3.getArea(width, height));
}
}