I am writing a java program, that needs some final variables. The java class must be a singleton object. And I can't directly initialize the final variable. Here is my code:
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;
}
}
And I would like to know whether if I can do like this or not:
private final Wheel WHEEL_TYPE = getWheelType();
That is my first question.
And the next thing is, when I run it I am getting nullPointerException at:
price.getAmount()
in public Wheel getWheelType()
method.
I am initializing price using a public constructor.
I am initilizing the class in some other class like this:
Car car = Car.getInstance(price);
Here I verified that both the price object and price.getAmount() are not null.
Can anyone guide me what am I doing wrong? Thanks