| 284 | |
| 285 | ==== Class containment |
| 286 | Sometimes it's useful to model the containment relationship between classes. For example, consider the following classes: |
| 287 | |
| 288 | Plane.java: |
| 289 | {{{ |
| 290 | import java.util.ArrayList; |
| 291 | |
| 292 | public class Plane { |
| 293 | ArrayList<Passenger> passengers; |
| 294 | int seats; |
| 295 | |
| 296 | public Plane(int seats) { |
| 297 | this.seats = seats; |
| 298 | passengers = new ArrayList<>(); |
| 299 | } |
| 300 | |
| 301 | public void board(Passenger p) { |
| 302 | if (passengers.size() < seats) { |
| 303 | passengers.add(p); |
| 304 | } else { |
| 305 | System.out.println("Sorry, plane is full."); |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | public int weight() { |
| 310 | int w=0; |
| 311 | for (Passenger p:passengers) { |
| 312 | w += p.weight; |
| 313 | } |
| 314 | return w; |
| 315 | } |
| 316 | } |
| 317 | }}} |
| 318 | |
| 319 | Passenger.java |
| 320 | {{{ |
| 321 | public class Passenger { |
| 322 | public int weight; |
| 323 | String name; |
| 324 | |
| 325 | public Passenger(String name, int weight) { |
| 326 | this.name = name; |
| 327 | this.weight=weight; |
| 328 | } |
| 329 | } |
| 330 | }}} |
| 331 | |
| 332 | Containment.java |
| 333 | {{{ |
| 334 | public class Containment { |
| 335 | public static void main(String args[]) { |
| 336 | Plane puddleHopper = new Plane(10); |
| 337 | Passenger p1 = new Passenger("Bob", 180); |
| 338 | Passenger p2 = new Passenger("Alice", 135); |
| 339 | |
| 340 | puddleHopper.board(p1); |
| 341 | puddleHopper.board(p2); |
| 342 | |
| 343 | System.out.println("Passengers weigh "+puddleHopper.weight()+" lbs"); |
| 344 | } |
| 345 | } |
| 346 | }}} |
| 347 | |