问题:
有两个篮子,分别为A 和 B,篮子A里装有鸡蛋,篮子B里装有苹 果,请用面向对象的思想实现两个篮子里的物品交换
代码
package cn.ljh.algorithmic;/*** author JH*/
public class Demo07
{public static void main(String[] args){//创建篮子Basket A = new Basket("【A篮子】");Basket B = new Basket("【B篮子】");//装载物品A.load("【鸡蛋】");B.load("【苹果】");//交换物品A.change(B);//展示A.show();B.show();}//篮子static class Basket{public String name; // 篮子名称private Goods goods; //篮子中所装的物品//只创建篮子的构造器public Basket(String name){this.name = name;System.err.println(name + "篮子被创建");}//把物品装到篮子里的函数public void load(String name){goods = new Goods(name);System.err.println(this.name + "装载了" + name + "物品");}//交换方法public void change(Basket B){System.err.println(this.name + "和" + B.name + "中的物品发生了交换");String tmp = this.goods.getName();this.goods.setName(B.goods.getName());B.goods.setName(tmp);}//打印交换后篮子里面的物品public void show() {System.err.println(this.name + "中有" + goods.getName() + "物品");}}//物品类static class Goods{private String name; // 物品名称//get\set 方法public String getName(){return name;}public void setName(String name){this.name = name;}//构造器public Goods(String name){this.name = name;}}}