我已经开始学习java并尝试编写一些代码。现在我想在调用此构造函数之前调用 box(negative ) 时抛出错误以减少不必要的计算时间,但它向我显示了此错误,
constructor call must be the first statement in a constructor error solution
我知道构造函数必须是第一件事,但是我不能在它之前抛出错误吗?或者我是否必须一次又一次地编写代码,而不是直接使用 this() 这是我的课
package oops;
import java.io.*;
class Box {
double weight;
double height;
double depth;
void vol () {
double vol = this.depth * this.height * this.weight;
System.out.print(" volume is :" + vol);
}
/**
* triggers Box(double depth) method with depth as 30
*/
Box(){
this(30);
}
/**
* triggers Box(double depth, double height) method with height as 40
* @param depth the desired depth of box
*/
Box(double depth){
this(depth, 40);
}
/**
* triggers Box(double depth, double height, double weight) method with weight as 50
* @param depth the desired depth of box
* @param height the desired height of box
*/
Box(double depth, double height){
this(depth, height, 50);
}
/**
* populates the 3 parameters in the class, given its depth, height and weight
* @param depth the desired depth of box
* @param height the desired height of box
* @param weight the desired weight of box
* @throws IllegalArgumentException if any parameter is negative
*/
Box(double depth, double height, double weight){
if(depth<=0)
throw new IllegalArgumentException("Negative depth size: " + depth);
if(height<=0)
throw new IllegalArgumentException("Negative height size: " + height);
if(weight<=0)
throw new IllegalArgumentException("Negative weight size: " + weight);
this.depth = depth;
this.height = height;
this.weight = weight;
}
}
我已经修改了代码以在 Box(双倍深度、双倍高度、双倍重量) 方法中抛出错误,但是在任何先前的构造函数到达此方法之前我无法抛出错误,例如 Box(-4) 或 Box(1, -5)
如果你想要这样,你应该让你的所有构造函数
private
(这样除了你之外没有人可以调用它们),然后创建一个public static
允许你构建对象的方法,该方法在调用构造函数之前执行检查。基本上:
private Box() {
//standard code
}
private Box(double depth) {
//standard code
}
public static Box create(/*parameters*/) {
//check parameters first
//if all good call constructor, else throw
}
但是,为了让您清楚,在构造函数之前或内部进行抛出并不会节省任何计算时间。 这更像是代码风格的问题而不是优化的问题。