不幸的是,我对默认构造函数的理解并不自信。 我进行了广泛的搜索,以找到提供说明的资料,以符合我对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
} //课程结束
答案 0 :(得分:0)
如果不使用它,则应将其删除。有时您需要创建空对象来设置后验属性,但是如果您根本不使用它,那就没有意义了
答案 1 :(得分:0)
制作默认构造函数的目的有时是后端的东西,被认为是“良好的编程习惯”,不,您不必在主体中使用默认构造函数,实际上,如果没有默认构造函数,您的代码也可以正常运行将其注释掉,然后重新运行测试仪,您会发现它运行正常。