为什么需要两个构造函数的解释

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

[不幸的是,我对默认构造函数的理解并不自信。我进行了广泛的搜索,以找到提供说明的资料,以符合我对Java语言的个人学习要求。但是,完成分配后,由于我自己对默认构造函数的需求而感到多余,我觉得我可能不符合分配标准。这就是为什么我觉得我一起误解了不同类型的构造函数的概念。我已经按照任务分配创建了两个构造函数。一种不带任何参数并将实例变量初始化为默认值的变量。另一个在主方法中创建新对象时,该参数接受参数以将值赋给对象变量。如果在main方法中从未使用默认构造函数,为什么要为该对象创建默认构造函数?下面是我的代码示例:

public class Circle {
    private double x;   // declaring variable to hold value of x coordinate
    private double y;   // Variable to hold value of y coordinate
    private double r;   // Variable to hold value of the radius of a circle

    /* default constructor */

    Circle() {
        x = 0.0;
        y = 0.0;
        r = 0.0;
    }

     /* constructor takes in three parameters and sets values for variables x, y, and r */

    public Circle(double x, double y, double r) {
        this.x = x;
        this.y = y;
        this.r = r;
    }

 // test class created for main method

public class TestCircle {
    public static void main (String[] args){
        Circle c1 = new Circle(2.0,3.0,9.0);
        System.out.println();
        System.out.println(" A circle object has been created with the following attributes:");
        c1.printAttributes();
        System.out.println();
        System.out.println("The circle is tested for the maximum radius of 8.0...");
    c1.setRadius(8.0);
    System.out.println();
    System.out.println("... since the radius is more than the allowable maximum, the new attributes for the Circle are:");
    c1.printAttributes();
    System.out.println();
    System.out.println("The area of the Circle is " + c1.area());
    System.out.println("The Circumference of the circle is " + c1.circumference());
    System.out.println();
    System.out.println("The origin of the circle is now moved by a specified amount...");
    c1.move(6,-7);
    System.out.println();
    System.out.println("The new attributes of the circle are:");
    c1.printAttributes();
    System.out.println();
    System.out.println("Testing if the point (10,-20) is inside the circle...");
    System.out.println();
    if (c1.isInside(10,-20)){
        System.out.println("The point (10,-20) is inside the circle");
    }
    else {
        System.out.println("The point (10,-20) is not inside the circle");
    }
} // end of main

} //课程结束

constructor default
2个回答
0
投票

如果不使用它,则应将其删除。有时您需要创建空对象来设置后验属性,但是如果您根本不使用它,那就没有必要了


0
投票

制作默认构造函数的目的有时是为了后端的东西,被认为是“良好的编程习惯”,不,您在主体中不使用默认构造函数,实际上,您的代码可以在没有默认构造函数注释的情况下正常运行退出并重新运行测试仪,您会发现它运行正常。

© www.soinside.com 2019 - 2024. All rights reserved.