http://www.verejava.com/?id=16992784958543
/** 知识点: 对象数组 1. 对象数组的使用 2. 对象数组的foreach 增强for循环 3. 可变参数 题目:乘客一次只能带2个箱子免费上飞机 思路: 1. 抽象出类 乘客(Customer) , 箱子(Box) 2. 乘客和箱子的关系 1对2的关系 Box->Customer*/public class Array { 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.getDe ion()); } //测试可变参数 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.getDe ion()); } }}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 de ion;//描述 public Box(String de ion) { this.de ion = de ion; } public String getDe ion() { return this.de ion; } public void setDe ion(String de ion) { this.de ion = de ion; } 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; }} 继续阅读与本文标签相同的文章
上一篇 :
Java 面向对象 之 代码块
-
DNN设置皮肤出错后如何还原默认皮肤
2026-05-25栏目: 教程
-
DNN模块开发入门指导
2026-05-25栏目: 教程
-
“SQL Server does not allow remote connections”错误的解决
2026-05-25栏目: 教程
-
DNN发邮件通知4.8.2有漏洞,最好升级到新版本
2026-05-25栏目: 教程
-
如何去除Search Skin ojbect中的"web"和"site"选项按键
2026-05-25栏目: 教程
