package com.yenange.t2;
import java.util.ArrayList;
import java.util.List;
public class FruitTest {
// 3. 有一个水果箱(box),箱子里装有水果(fruit)。每一种水果都有不同的重量(weight)和颜色(color),
// 水果有:苹果(apple),梨(pear)。可以向水果箱(box)里添加水果(addFruit),也可以取出水果(getFruit)。
// 请编写java代码实现上述功能。
public static void main(String[] args) {
Box box = new Box();
box.addFruit(new Apple(25, "红色"));
box.addFruit(new Pear(30, "黄色"));
System.out.println("取之前的水果箱的总数量:"+box.num);
for (Fruit fruit : box.list) {
System.out.println(fruit);
}
System.out.println("/n取出来的水果是:");
Fruit fruit=box.getFruit(1);
System.out.println(fruit);
System.out.println("取之后的水果箱的总数量:"+box.num);
}
}
class Box {
List list = new ArrayList();
public int num = 0;
public Box() {
}
public void addFruit(Fruit f) {
list.add(f);
num++;
}
public Fruit getFruit(int index) {
Fruit f = list.get(index);
list.remove(f);
num--;
return f;
}
}
class Fruit {
private int weight;
private String color;
public Fruit(int weight, String color) {
this.weight = weight;
this.color = color;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String toString() {
return "水果名称:" + this.getClass().getSimpleName() + "/t颜色:"
+ this.getColor() + "/t重量:" + this.getWeight()+"克";
}
}
class Apple extends Fruit {
public Apple(int weight, String color) {
super(weight, color);
}
}
class Pear extends Fruit {
public Pear(int weight, String color) {
super(weight, color);
}
}