提问人:val didar singh 提问时间:11/7/2023 最后编辑:Mark Rotteveelval didar singh 更新时间:11/7/2023 访问量:63
构造函数调用必须是构造函数错误替代项中的第一个语句
constructor call must be the first statement in a constructor error alternative
问:
我已经开始学习Java,并试图编写一些代码。在调用此构造函数之前,我想在调用 box(negative) 时抛出错误,但它向我显示此错误。
构造函数调用必须是构造函数错误中的第一个语句 溶液
我知道构造函数必须是第一件事,但是我不能在它之前抛出错误,或者我必须一次又一次地编写代码,而不是直接使用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(double depth, double height, double weight) 方法中抛出错误,但是在任何先前的构造函数到达此方法(如 Box(-4) 或 Box(1, -5))之前,我无法抛出错误。
答:
2赞
Matteo NNZ
11/7/2023
#1
如果你愿意,你应该创建所有的构造函数(这样除了你之外没有人可以调用它们),然后创建一个允许你构建对象的方法,该对象在调用构造函数之前执行检查。基本上: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
}
但是,为了向您明确说明,您不会通过在构造函数之前或内部抛出来节省任何计算时间。 与其说是优化,不如说是代码风格问题。
1赞
Chaosfire
11/7/2023
#2
为了完整起见,如果验证通过,则可以使用返回输入的验证方法:
private static double validate(double value) {
if (value <= 0) {
throw new IllegalArgumentException("message");
}
return value;
}
并像这样使用它:
Box(double depth) {
this(validate(depth), 40);
}
受 Objects.requireNonNull()
的启发。
需要明确的是,我怀疑收益是否足以让它变得值得,除非你想为项目采用这样的代码风格。TBH Mateo 采用静态工厂方法的方法更简洁。
评论