thufir wrote:
> Hmm, I was taking the example from a book, so that's kinda frustrating.
> Maybe I misinterpreted it. I haven't had a chance to google it, but
> you'd just not create the Guests class which extends ArrayList?
The principle, elucidated in pretty much those words in /Effective Java/
by
Joshua Bloch, is a guideline rather than a rule. "Prefer composition"
means
that in most designs it works better to include an element of type List
than
to extend a List type. Sometimes the "is-a" relation****p is so strong and
evident that you absolutely must inherit, but most of the time it makes at
least as much sense to use "has-a", and that makes maintenance easier.
> public class Guests extends ArrayList <Guest>
> {
>
> }
Since Guests does nothing to add to ArrayList, it probably doesn't need a
whole new type.
public class Lab2
{
private final List <Guest> guests = new ArrayList <Guest> ();
public void print()
{
for ( Guest g : guests )
{
System.out.println( g );
}
}
public boolean add( Guest g )
{
if ( g == null )
{ throw new NullPointerException( "null Guest" ); }
return guests.add( g );
}
public static void main( String args [] )
{
Lab2 lab = new Lab2();
for ( int ix = 0; ix < 9; ++ix )
{
lab.add( new Guest() );
}
lab.print();
}
}
--
Lew


|