如何构建一个让用户确定半径的 "Circle" 对象?

How to build a "Circle" object that lets the user determine the radius?

我正在学习面向对象的编程class,但我在理解如何构建一个让用户声明半径的圆形对象时遇到了一些困难。

我创建了一个数据 class 并在其中放入了我的实例变量、我的 getter 和 setter 方法、我的构造函数,然后是基本的计算函数方法来计算给定半径的圆的面积和周长。 这是 class:

package shapesoo;
public class CircleDataClass {
private double radius;

public double getRadius() {
    return radius;
    }

public void setRadius(double radius) {
    this.radius = radius;
    }

public CircleDataClass(double radius) {
    this.radius = radius;
    }

public double getArea(){
    return Math.PI * radius * radius;
    }

public double getCircumference(){
    return 2 * Math.PI * radius;
    }
}

然后,我正在创建一个测试 class 来构建具有给定半径的圆,在我的主要方法中,我创建了新的圆对象:

CircleDataClass myCircle = new CircleDataClass(radius);

我没有在此测试中的任何地方声明半径 class,所以这就是我收到 运行 时间错误的原因。但我想要的是用户输入我在构造函数中拥有的那个半径参数的值,然后将该半径传递给这个圆对象。我是否在 main class 中创建了一个单独的方法来询问半径值?我想我对 getters/setters/cosntructors 正在做什么以及如何将半径变量传递给不同的 classes 感到困惑。

编辑:如果我把它放进去,我的数据class中的实例变量是否被使用了?

public static void main(String[] args) {

    String shapeType = getShape();

    if (shapeType.equalsIgnoreCase("Circle")){
        String r = JOptionPane.showInputDialog("What is the radius: ");
        double radius = Double.parseDouble(r);
        CircleDataClass myCircle = new CircleDataClass(radius);

    }
}

我知道如何在不使用面向对象原则的情况下做到这一点,我知道这对你们中的许多人来说似乎很基础,但我将不胜感激任何帮助。

I don't have radius declared anywhere in this test class so that's why I am getting a run-time error.

好的,这很正常

But what I want is a user to input the value for that radius parameter that I have in my constructor and then have that radius passed to this circle object. Do I create a separate method in my main class that asks for the value of the radius?

是的。基本上,您可以读取用户输入数字的标准输入,然后用它实例化圆圈。参见 Scanner class。

I think I am getting confused with what getters/setters/cosntructors are doing and how to pass the radius variable around to different classes.

  • 构造函数用于创建和初始化 class 的实例。
  • getter(s) 提供对实例属性的只读访问权限。在你的情况下,如果你想检查特定圆实例的半径是多少,你可以通过 myCircle.getRadius().
  • setter(s)的作用是变异一个实例,即改变内部属性。使用 setter 可能不是好的做法,当需要更改 属性 时创建一个新对象可能会更好。这实际上取决于您的设计和上下文。