我有一个构造函数:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
我想设置最便宜的水果。
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");
}
}
}
这会在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;
}
处死,并且空指针异常。我该如何正确设置?
答案 0 :(得分:0)
对于一个人来说,将cheapestFruit作为Fruit Object的一部分是一种不好的做法,因为无论何时创建对象,都必须创建另一个最便宜的水果对象。这就是你得到nullpointer异常的原因
解决方案:使用以下方法将cheapestFruit更改为static:
public static Fruit CHEAPEST_FRUIT = null;
现在,每创造一些水果,你只有一个最便宜的水果实例。
现在是经过纠正的二传手:
public static void setCheapestFruit(Fruit fruit){
CHEAPEST_FRUIT = fruit;
}
另一件需要考虑的事情是:既然你有一个制定者,为什么要将变量cheapestFruit公之于众?
答案 1 :(得分:0)
简单地说,你不能在cheapestFruit
内Fruit
课。正如您所指出的那样,只会导致StackOverflowException。您应该如何保持代码的一致性,将cheapestFruit
变量保存在另一个实体中FruitStore
。
public class Fruit {
String name;
int price;
public Fruit(String name, int price){
this.name = name;
this.price = price;
}
}
public class FruitStore {
public Fruit cheapestFruit;
public Fruit expensiveFruit;
public void setCheapestFruit(Fruit fruit){
if(fruit.price < cheapestFruit.price){
cheapestFruit = fruit;
}else{
System.out.print("It's not cheapest");
}
}
}
或者,如果你真的想把所有东西放在同一个不太有意义的课堂上,你必须创建不同的构造函数来做一些解决方法。