Java实验一—设计一个名为Rectangle的类表示矩形

(仅记录自己的学习之路)
设计一个名为Rectangle的类表示矩形,这个类包括:
(1) 一个名为int类型的静态变量numberOfRectangle,记录创建的矩形的个数;
(2) 两个名为width和height的double型数据域,它们分别表示矩形的宽和高。width和height的默认值都为1。
(3) 创建默认矩形的无参构造方法。
(4) 一个创建width和height为指定值的矩形的构造方法。
(5) 两个数据域的get和set方法。
(6) 一个名为getArea()的方法返回这个矩形的面积。
(7) 一个名为getPerimeter()的方法返回周长。
(8) 一个名为getNumberOfRectangle()的静态方法,获取已经创建的矩形对象的个数。

编写一个测试程序,分别使用两个构造方法,创建两个Rectangle对象,并按照下面的样例输出结果:
Java实验一—设计一个名为Rectangle的类表示矩形_第1张图片
代码如下:

package TestRectangle;

import java.util.Scanner;

class Rectangle{
	private static int numberOfRectangle;     //记录创建的矩形的个数
	private double width = 1.0;               //矩形的宽,默认值为1.0
	private double height = 1.0;              //矩形的长,默认值为1.0
	Rectangle(){
		numberOfRectangle++;                  //创建矩形对象个数叠加
	}
	public Rectangle(double width, double height) {
		this.width = width;
		this.height = height;                  //创建width和height为指定值的矩形
	}
	public double getWidth() {
		return width;                         //返回矩形的宽
	}
	public void setWidth(double width) {
		this.width = width;                    //设置矩形的宽
	}
	public double getHeight() {
		return height;                        //返回矩形的高
	}
	public void setHeight(double height) {
		this.height = height;                  //设置矩形的高
	}
	public double getArea() {
		return this.height * this.width;     //返回矩形的面积
	}
	public double getPerimeter() {
		return 2 * (this.height + this.width);  //返回矩形的周长
	}
	public static int getNumberOfRectangle() {
		return numberOfRectangle;           //获取已创建矩形对象的个数
	}
}

public class testRectangle {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		Rectangle r1 = new Rectangle();       //创建矩形对象r1
		r1.setHeight(input.nextDouble());      //设置矩形的高
		r1.setWidth(input.nextDouble());       //设置矩形的宽
		System.out.println("宽为:" + r1.getWidth() + "       " + "高为:" + r1.getHeight() + "       " + "周长为:" + 
		r1.getPerimeter() + "    " + "面积为:" + r1.getArea() + "      " + "矩形个数为:" + r1.getNumberOfRectangle());
		Rectangle r2 = new Rectangle();       //创建矩形对象r2
		r2.setWidth(input.nextDouble());      //设置矩形的宽
		r2.setHeight(input.nextDouble());     //设置矩形的高
		System.out.println("宽为:" + r2.getWidth() + "       " + "高为:" + r2.getHeight() + "       " + "周长为:" 
		+ r2.getPerimeter() + "    " + "面积为:" + r2.getArea() + "      " + "矩形个数为:" + r2.getNumberOfRectangle());
	}
}

你可能感兴趣的:(java,编程语言)