有一个水果箱(Box),箱子里装有水果(Fruit),每一种水果都有不同的重量和颜色,水果有:苹果,梨,橘子。每个苹果(Apple)都有不同的重量和颜色,每个橘子(Orange)有不同的重量和颜色

public class Fruit {
	private String name;
	private String color;
	private int weight;
	//set get方法
	public String getColor() {
		return color;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public int getWeight() {
		return weight;
	}
	public void setWeight(int weight) {
		this.weight = weight;
	}
	
	//构造方法
	public Fruit() {}
	public Fruit(String name,String color,int weight) {
		this.name=name;
		this.color = color;
		this.weight = weight;
	}
	//重写
	public String toString() {
		
		return getName()+"  "+getWeight()+"  "+getColor();
	}
}

public class Apple extends Fruit {
	public Apple(String name,String color,int weight) {
		super(name,color,weight);
	}
	
}
public class Pear extends Fruit{

	public Pear(String name,String color,int weight) {
		super(name,color,weight);
		
	}
}
public class Orange extends Fruit {
	public Orange(String name,String color,int weight) {
		super(name,color,weight);
		
	}
}
import java.util.ArrayList;

public class Box {
	ArrayList<Fruit> flist = new ArrayList<Fruit>();
	//添加水果方法
	public void addFruit(Fruit fruit) {
		flist.add(fruit);
		
	}
	//取出水果方法
	public void  getFruit(Fruit fruit) {
		flist.remove(fruit);
		
	}
	//显示
	public void show() {
		for(Fruit fruit : flist) {
			System.out.println(fruit);
		}
	}
		
	public static void main(String[] args) {
		Fruit f1 = new Apple("apple","red",3);
		Fruit f2 = new Pear("pear","blue",6);
		Fruit f3 = new Orange("orange","yellow",8);
	
		Box b = new Box();
		b.addFruit(f1);
		b.addFruit(f2);
		b.addFruit(f3);
		System.out.println("显示水果:...............");
		b.show();
		b.getFruit(f3);
		System.out.println("取出水果后:............");
		b.show();
	}
	}

  • 6
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值