import java.util.ArrayList;
import java.util.List;
public class Apple {
private static String color;
private static int weight;
public Apple(String color, int weight){
this.color = color;
this.weight = weight;
}
public int getWeight(){
return weight;
}
public String getColor(){
return color;
}
public interface AppleFormatter{
String accept(Apple a);
}
public static class AppleFancyFormatter implements AppleFormatter{
public String accept(Apple apple){
String characteristic = apple.getWeight() > 150 ? "heavy" : "light";
return "A " + characteristic + " " + apple.getColor() + " apple";
}
}
public static class AppleSimpleFormatter implements AppleFormatter{
public String accept(Apple apple){
return "An apple of " + apple.getWeight() + "g";
}
}
public static void prettyPrintApple(List<Apple> inventory, AppleFormatter formatter){
for(Apple apple: inventory){
String output = formatter.accept(apple);
System.out.println(output);
}
}
public static void main(String[] args){
List<Apple> arrayList = new ArrayList<>();
Apple app1 = new Apple("green", 155);
Apple app2 = new Apple("yellow", 160);
Apple app3 = new Apple("red", 130);
arrayList.add(app1);
arrayList.add(app2);
arrayList.add(app3);
prettyPrintApple(arrayList, new AppleFancyFormatter());
prettyPrintApple(arrayList, new AppleSimpleFormatter());
}
}
以下代码打印: 一个浅红色的苹果 一个浅红色的苹果 一个浅红色的苹果 一个130克的苹果 一个130克的苹果 一个130克的苹果
我注意到了我的数组不能正确迭代的倾向,但是我创建的最后一个对象不断被打印出来。我不知道为什么会这样。我错过了什么?enter code here
答案 0 :(得分:5)
你的领域是静态的!
private static String color;
private static int weight;
所以所有的苹果都有相同的颜色和重量!删除static关键字,一切正常!