第九章第一题(Rectangle类)(Rectangle class)

第九章第一题(Rectangle类)(Rectangle class)

  • 9.1(Rectangle类)遵照9.2节中 Circle 类的例子,设计一个名为 Rectangle 的类表示矩形。
    这个类包括:

    • 两个名为 width 和 height 的 double 型数据域,它们分别表示矩形的宽和高。width 和 height 的默认- 值都为1。
    • 一个创建默认矩形的无参构造方法。
    • 一个创建 width 和 height 为指定值的矩形的构造方法。
    • 一个名为 getArea() 的方法返回这个矩形的面积。
    • 一个名为 getPerimeter() 的方法返回周长。

    画出该矩形的 UML 图并实现这个类。编写一个测试程序,创建两个 Rectangle 对象——一个矩形的宽为 4 而高为 40,另一个矩形的宽为 3.5 而高为 35.9 。按照这个顺序显示每个矩形的宽、高、面积、周长。

  • 9.1(rectangle class) following the example of circle class in Section 9.2, design a class named rectangle to represent rectangle.
    This class includes:

    • Two double data fields named width and height represent the width and height of the rectangle, respectively. The default values for width and height are 1.
    • A nonparametric construction method for creating default rectangles.
    • A construction method for creating a rectangle with the specified values of width and height.
    • A method called getarea() returns the area of the rectangle.
    • A method called getperimeter () returns the perimeter.

    Draw a UML diagram of the rectangle and implement the class. Write a test program and create two rectangle objects - one rectangle is 4 in width and 40 in height, and the other is 3.5 in width and 35.9 in height. Display the width, height, area, perimeter of each rectangle in this order.

  • 参考代码:

package chapter09;


public class Code_01 {
    
    
    public static void main(String[] args){
    
    
        Rectangle r1 = new Rectangle(4,40);
        System.out.println("宽为" + r1.weight + "高为" + r1.height + "的矩形周长是:" + r1.getPerineter() + ",面积是:" + r1.getArea());
        Rectangle r2 = new Rectangle(3.5,35.9);
        System.out.println("宽为" + r2.weight + "高为" + r2.height + "的矩形周长是:" + r2.getPerineter() + ",面积是:" + r2.getArea());
    }
}
class Rectangle{
    
    
    double weight = 1;
    double height = 1;
    Rectangle(){
    
    

    }
    Rectangle(double newweight,double newhieght){
    
    
        weight = newweight;
        height = newhieght;
    }
    double getArea(){
    
    
        return height * weight;
    }
    double getPerineter(){
    
    
        return 2 * (height + weight);
    }
}

  • 结果显示:
宽为4.0高为40.0的矩形周长是:88.0,面积是:160.0
宽为3.5高为35.9的矩形周长是:78.8,面积是:125.64999999999999

Process finished with exit code 0

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/jxh1025_/article/details/109256806