Java 对象和类初学者

标签 java class object

嘿伙计们,我们刚刚开始介绍我类(class)中的对象和类。我非常了解创建该类的新实例。然而,我无法理解其数据字段和方法。这是我写的书中的一个样本。我不太明白我评论的部分:“//构造一个半径为1的圆。原因是b.c我已经在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;,则可以忽略该构造函数。第二个允许开发人员将参数传递给 double 类型的 SimpleCircle(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。其余的使用传入的半径值或第二个构造函数。

关于Java 对象和类初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22080610/

相关文章:

java - 为什么在定义 hashCode() 和 equals() 后我的代码仍然比较链接

java - 节点无法解析为类型

java - 如何将 HashMap 复制到具有不同引用的 ArrayList

java - 使用 Apache common-cli 解析参数

java - 为什么会出现这样的输出呢?

python - 通过 find_element_by_class_name 单击按钮不起作用 python selenium webdriver 不工作

javascript - 将数组中的所有对象合并为一个

java - Blue J,我的 listMembers 方法没有从我的数组列表中打印出正确的数据

java - 如何在 Apache Tomcat 服务器中保护我的代码?

java - 没有经验的 java 用户请求有关类的建议