I have a constructor:
private String name;
private int price;
public Fruit (String name, int price){
this.name = name;
this.price = price;
System.out.println("NAME/PRICE SET");
if (getCheapestFruit() == null){
setCheapestFruit(name, price);
System.out.println("CHEAPEST NAME/PRICE INITIALIZED");
} else {
if(getCheapestFruit().price> price){
setCheapestFruit(name, price);
System.out.println("CHEAPEST NAME/PRICE SET");
}
}
}
And I want to set the cheapestFruit.
public Fruit cheapestFruit = null;
public Fruit getCheapestFruit(){
return this.cheapestFruit;
}
public void setCheapestFruit(String name, int price){
this.cheapestFruit.price = price;
this.cheapestFruit.name = name;
}
And this die at this.cheapestFruit.price = price;
with null pointer exception. How can I set it correctly?