Re: Interfaces and aggregation

From: Adam (NOTFORSPAM.a_szczeblewski_at_poczta.onet.pl)
Date: 01/30/04


Date: Fri, 30 Jan 2004 15:54:53 +0100


> Considering it doesn't make any sense for a Cabin to exist without a
> Ship, I'd pass the Ship to the constructor of Cabin, thus:
>
> class Cabin implements Query {
> private Ship myShip;
>
> public Cabin(Ship ship) {
> myShip = ship;
> }
>
> public String getQuery() {
> return myShip.getQuery();
> }
> }

Another possibility is to make Cabin a public nested
(inner) class of ship. Then it automaticaly has a
reference to its owning ship. Even creating
cabins is safer then - you have to have a ship
to create a cabin:
Ship ship = new Ship();
Ship.Cabin cabin = ship.new Cabin();
There is no way you can create a cabin not
belonging to any ship.
As for Barry's suggestion (above), it still would be
possible to do new Cabin(null). Even
if a NullPointerException was thrown from the Cabin's ctor
you would not know it until runtime.
With nested class it is the compiler's (not programmer's) responsibility
to assure that each cabin has an owning ship.

Disadvantage of this approach is having one big source file
for two classes. That's why probably many programmers
avoid this way of implementing aggregation (yes, me too)

Adam



Relevant Pages

  • Re: Some Thoughts on the Norwegian Spirit (Long)
    ... Bermuda/King's Wharf, At Sea, New York (8 Night Voyage) ... THE SHIP: ... next to our cabin), and we could definitely feel a difference between ... the Norwegian Spirit has a full compliment of Specialty ...
    (rec.travel.cruises)
  • Azamara Journey trip report
    ... Tours for a quote I had expected the price was going to be out of range ... of what I was willing to pay for a cruise to Bermuda during hurricane ... Azamara also now has the other R ship ... and butlers in every cabin. ...
    (rec.travel.cruises)
  • Re: Azamara Journey trip report
    ... of what I was willing to pay for a cruise to Bermuda during hurricane ... Azamara also now has the other R ship ... and butlers in every cabin. ... the pool deck. ...
    (rec.travel.cruises)
  • Re: Azamara Journey trip report
    ... Tours for a quote I had expected the price was going to be out of range ... of what I was willing to pay for a cruise to Bermuda during hurricane ... Azamara also now has the other R ship ... and butlers in every cabin. ...
    (rec.travel.cruises)
  • Re: Miracle Review - March 5-12, 2006
    ... The Sheraton offered a free shuttle to the ship, but it only held a few ... porters at the cruise terminal. ... The cabin was very nice. ... Food: Overall, a positive review. ...
    (rec.travel.cruises)