我正在编写一个需要一些最终变量的java程序.java类必须是单例对象.我无法直接初始化最终变量.这是我的代码:
public class Car {
private Price price = null;
//Constructor
public Car(Price p) {
this.price = p;
}
//method to get the singleton
private static Car instance = null;
public static Car getInstance(Price p) {
if(instance == null) {
instance = new ExcelUtil2(p);
}
return instance;
}
//declare & initialize final variable
private final Wheel WHEEL_TYPE = getWheelType();
//get value of the final variable
public Wheel getWheelType() {
Wheel wheel = Car.createWheel();
if(price.getAmount() > 30000){
wheel.setWheelType("Alloy");
}else{
wheel.setWheelType("Alluminium");
}
return wheel;
}
}
Run Code Online (Sandbox Code Playgroud)
而且我想知道我是否可以这样做:
private final Wheel WHEEL_TYPE = getWheelType();
Run Code Online (Sandbox Code Playgroud)
这是我的第一个问题.
接下来就是,当我运行它时,我得到nullPointerException:
price.getAmount()
Run Code Online (Sandbox Code Playgroud)
在public Wheel getWheelType()方法中.
我正在使用公共构造函数初始化价格.
我在这样的其他类中初学化类:
Car car = Car.getInstance(price);
Run Code Online (Sandbox Code Playgroud)
在这里,我验证了price对象和price.getAmount()都不为null.
谁能指导我,我做错了什么?谢谢
没有什么本质上的错误
private final Wheel WHEEL_TYPE = getWheelType();
Run Code Online (Sandbox Code Playgroud)
但是,一般情况下(如Java教程中所推荐的),当您这样做时,您应该调用无法覆盖的final方法- 类中的方法,static方法,private方法或方法final.
但是,使用您的特定代码存在问题.在执行中getWheelType(),您正在调用price.getAmount()并price在构造函数的主体中初始化.不幸的是,对于您的设计,字段实例初始化程序在构造函数的主体之前执行,因此您将price.getAmount()在price初始化之前结束调用.
我建议您在赋值WHEEL_TYPE之后将赋值移动到构造函数内部price.
| 归档时间: |
|
| 查看次数: |
831 次 |
| 最近记录: |