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

匿名 (未验证) 提交于 2019-12-03 00:34:01
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(); 	} 	 } 

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); 		 	} }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!