我需要帮助创建一个带有私有实例变量但公共方法和构造函数的 Rectangle 类

问题描述 投票:0回答:1

我是使用java的新手,我需要创建一个名为矩形的类,但我使用的代码似乎不起作用,并且类的注释没有帮助。我觉得这和我的方法有关,因为我不太了解这些。

班级需要遵循以下要求: 使用以下实例变量和公共构造函数创建一个名为矩形的类:

  • 宽度,双

  • 高度,双

  • 一个名为 sideLength 的具有一个参数(双精度)的构造函数,它将宽度和高度设置为 sideLength。

  • 具有两个参数宽度和高度(双精度)的构造函数,它将宽度和高度设置为传递的相应值。

  • 不带参数的公共方法computeArea,以双精度形式返回 Rectangle 的面积

  • 不带参数的公共方法computePerimeter,以双精度形式返回 Rectangle 的周长

  • 不带参数的公共方法 getHeight,以 double 形式返回 Rectangle 的高度

  • 不带参数的公共方法 getWidth,以 double 形式返回 Rectangle 的宽度

我不需要创建一个 main 方法,因为它已经提供了。

这是我正在使用的代码,但我不断收到错误消息,提示无法从computeArea方法及其向下找到高度。

 class Rectangle{
     
     private static double width;
     private static double heigth;
     
     public Rectangle(double sideLength) {
         
         Rectangle width = new Rectangle(sideLength);
         Rectangle height = new Rectangle(sideLength);
     }
         
     public Rectangle(double width, double height){
         width = width;
         height = height;
     }    

     public double computeArea() {
         return height * width;
     }
         
     public double computePerimeter() {
         return 2 * (height + width);
     }
         
     public double getHeight() {
         return height;
     }
     
     public double getWidth() {
         return width;
     }
     
 }
java class methods constructor instance-variables
1个回答
0
投票

不要将私有变量设置为静态,否则它们将被 Rectangle 的所有实例共享。

class Rectangle{
     
     private double width;
     private double height;
     
     public Rectangle(double sideLength) {
         
         this.width = sideLength;
         this.height = sideLength;
     }
         
     public Rectangle(double width, double height){
         this.width = width;
         this.height = height;
     }    

     public double computeArea() {
         return height * width;
     }
         
     public double computePerimeter() {
         return 2 * (height + width);
     }
         
     public double getHeight() {
         return height;
     }
     
     public double getWidth() {
         return width;
     }
 }

在其他代码中使用它:

Rectangle square = new Rectangle(1.0);
square.computeArea();
Rectangle rectangle = new Rectangle(1.0, 2.0);
rectangle.computeArea();
© www.soinside.com 2019 - 2024. All rights reserved.