Design Patterns Java™ Workbook

(Michael S) #1
Appendix B. Solutions

Introducing Construction (Chapter 14)...................................................................................................


SOLUTION 14.1....................................................................................................................................


Special rules regarding constructors include the following.



  • You must use new to invoke a constructor.

  • Constructor names must match the class name. This results in the oddity that, unlike
    most methods, constructor names normally begin with an uppercase letter.

  • If you do not supply a constructor for a class, Java will provide a default.

  • You can invoke other constructors with this() and super() so long as this
    invocation is the first statement in a constructor.


There are also several rules governing the order of field initialization and special rules for
the instantiation of arrays.


SOLUTION 14.2....................................................................................................................................


A constructor that allows Fountain to compile is:


public Fountain(String name)
{
super(name);
}


This constructor allows the Fountain class to compile, as it invokes the superclass's
constructor in its first statement. We have also corrected an important inconsistency in our
classes. By introducing a Firework constructor that accepts a name, we established that all
Firework objects must have a name. Logically, all fountains are fireworks, and all
Fountain objects must have a name if all Firework objects have a name. The constructor
in this solution respects the design of its superclass, accepting a name and passing it up so that
the superclass can uniformly apply it.


SOLUTION 14.3....................................................................................................................................


One way to provide default values for an object's attributes is to provide a constructor that
omits the attribute. That constructor can fill in the default value, passing control to another
constructor with this():


public Firework(String name)
{
this(name, DISPLAY);
}


public Firework(String name, Classification classification)
{
this.name = name;
this.classification = classification;
}

Free download pdf