大家好,所以我们才开始介绍我班上的对象和班级。我知道很好地创建该类的新实例。但是,它的数据字段和方法难以理解。这是我写出的书中的一个示例。我没有得到我应予赞扬的部分:“ //构造一个半径为1的圆。原因是在公元前,我已经在SimpleCircle类中声明了双倍半径,所以为什么还要再次编写SimpleCircle?我有点理解访问器,并且该程序的更改者,但请对此进行更简单的说明。

public class TestSimpleCircle {

    public static void main(String[] args) {

        SimpleCircle circle1 = new SimpleCircle();
        System.out.println("The area of the circle of radius " + circle1.radius + " is " + circle1.getArea());

        // create a circle with radius 25
        SimpleCircle circle2 = new SimpleCircle(25);
        System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea());

        // create a circle with radius 125
        SimpleCircle circle3 = new SimpleCircle(125);
        System.out.println("The area of the circle of radius " + circle3.radius + " is " + circle3.getArea());

        // Modify circle radius of second object
        circle2.setRadius(100);   //or circle2.setRadius(100);
        System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea());

    } // end main
} // end class


class SimpleCircle {
    double radius;

    // construct a circle with radius 1
    SimpleCircle() {
        radius = 1;

    }

    // construct a circle with a specified radius
    SimpleCircle(double newRadius) {
        radius = newRadius;

    }

    // return the are of this circle
    double getArea() {
        return radius * radius * Math.PI;

    }

    // return the perimeter of this circle
    double getPerimeter() {
        return 2 * radius * Math.PI;
    }

    // set a new radius for this circle
    void setRadius(double newRadius) {
        radius = newRadius;
    }

} // end class

最佳答案

之所以有两个SimpleCircle()语句,是因为一个是默认的构造函数,如果将double radius;更改为double radius = 1;,则从技术上讲可以省略该构造函数。第二种允许开发人员将参数传递给类型为SimpleCircle(double)double并将其分配给名为radius的字段。这两个SimpleCircle(...)语句都称为构造函数。

程序的示例输出:

The are of the circle of radius 1.0 is 3.141592653589793
The are of the circle of radius 25.0 is 1963.4954084936207
The area of the circle of radius 125.0 is 49087.385212340516
The area of the circle of radius 100.0 is 31415.926535897932


您可以在第一句话中看到它使用了默认构造函数,该构造函数将半径设置为1或1.0,因为它是double。其余的将传入的值用于radius或第二个构造函数。

08-05 13:04