您现在的位置是:首页 > 文章详情

Java 面向对象 之 对象数组

日期:2018-08-13点击:409

http://www.verejava.com/?id=16992784958543

/** 知识点: 对象数组 1. 对象数组的使用 2. 对象数组的foreach 增强for循环 3. 可变参数 题目:乘客一次只能带2个箱子免费上飞机 思路: 1. 抽象出类 乘客(Customer) , 箱子(Box) 2. 乘客和箱子的关系 1对2的关系 Box->Customer */ public class ObjectArray { public static void main(String[] args) { //实例化一个乘客 Customer c = new Customer("黎明"); //实例化两个箱子一个装衣服, 一个装书 Box clothBox = new Box("装衣服"); clothBox.setId(1); clothBox.setWeight(20); Box bookBox = new Box("装书"); bookBox.setId(2); bookBox.setWeight(30); //将箱子添加到乘客 c.addBox(clothBox); c.addBox(bookBox); //打印该乘客的信息 System.out.println("乘客姓名: " + c.getName()); System.out.println("箱子编号, 箱子重量, 箱子描述"); Box[] boxes = c.getBoxes(); for (Box box : boxes) { System.out.println(box.getId() + "," + box.getWeight() + "," + box.getDescription()); } //测试可变参数 Box[] boxes2 = { clothBox, bookBox }; c.setBoxes();//不传参数 c.setBoxes(clothBox);//传一个参数 c.setBoxes(boxes2);//传一个数组 boxes = c.getBoxes(); for (Box box : boxes) { System.out.println(box.getId() + "," + box.getWeight() + "," + box.getDescription()); } } } class Customer { private String name;//乘客名字 private Box[] boxes = new Box[2];//箱子属于乘客, 添加箱子引用 public Customer(String name) { this.name = name; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Box[] getBoxes() { return this.boxes; } //乘客携带添加的箱子 //返回值: 如果添加成功返回true 否则false public boolean addBox(Box box) { for (int i = 0; i < boxes.length; i++) { if (boxes[i] == null) { boxes[i] = box; return true; } } return false; } public void setBoxes(Box... boxes) { this.boxes = boxes; } } class Box { private float weight;//箱子的重量 private int id;//箱子的编号 private String description;//描述 public Box(String description) { this.description = description; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public float getWeight() { return this.weight; } public void setWeight(float weight) { this.weight = weight; } }

http://www.verejava.com/?id=16992784958543

原文链接:https://yq.aliyun.com/articles/625118
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章