package com.huang.algorithm; /** * 面向对象思想实现篮子物品交换 */ public class Demo04 { public static void main(String[] args) { Basket basket1 = new Basket("篮子1"); Basket basket2 = new Basket("篮子2"); basket1.load("鸡蛋"); basket2.load("苹果"); basket1.change(basket2); basket1.show(); basket2.show(); } } class Basket { public String name; private Goods goods; public Basket(String name) { this.name = name; System.out.println(name + " 篮子被创建"); } public void load(String name) { goods = new Goods(name); System.out.println(this.name + "装载了" + name + "物品"); } public void change(Basket basket){ System.out.println(this.name + " 和 " + basket.name + "中的物品发生了交换"); String tmp = this.goods.getName(); this.goods.setName(basket.goods.getName()); basket.goods.setName(tmp); } public void show() { System.out.println(this.name + "中的物品是:" + this.goods.getName()); } } class Goods { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Goods(String name) { this.name = name; } }标签:Basket,goods,装有,String,面向对象,篮子,public,name From: https://www.cnblogs.com/ningl666/p/18066600