对于上述问题,怎么初始化
时间: 2024-01-07 10:03:30 浏览: 28
在Rectangle类中,如果width和height是实例变量,则可以在构造函数中初始化它们。例如:
```
public class Rectangle {
private Double width;
private Double height;
public Rectangle(Double width, Double height) {
this.width = width;
this.height = height;
}
public double computeArea() {
return this.width * this.height;
}
}
```
在这个例子中,我们在Rectangle类的构造函数中初始化了width和height变量,这样在调用computeArea方法时,就不会出现空指针异常了。你可以在ShapeTest类中创建Rectangle对象的时候,传入width和height的值来初始化它们。
另外,如果你想要保证width和height不为null,也可以在Rectangle类的构造函数中添加一些检查,如果它们为null,则抛出IllegalArgumentException异常。例如:
```
public Rectangle(Double width, Double height) {
if(width == null || height == null) {
throw new IllegalArgumentException("Width and height cannot be null");
}
this.width = width;
this.height = height;
}
```
这样就可以在创建Rectangle对象的时候,确保width和height不为null,防止在计算面积时出现空指针异常。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)