Design Patterns Java™ Workbook

(Michael S) #1
Chapter 14. Introducing Construction

Figure 14.1. In certain conditions, Java will provide default constructors and default
constructor collaboration.

A problem arises if we add a constructor to the superclass. Suppose that we add a name
attribute to Firework and a constructor that accepts it:


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


After this change to Firework, the Fountain class will suddenly fail to compile. The
Fountain class defines no constructor, so Java will supply a default constructor. This
constructor makes a default call to super(), the superclass's default constructor. However,
this constructor no longer exists. Java supplies a default constructor only if the class has no
other constructor. By creating a constructor for Firework, we eliminate this class's default
constructor and thereby break the Fountain class.


CHALLENGE 14.2


Write a constructor for the Fountain class that allows it to successfully compile.

Java will not always insert a call to super() in a constructor. A constructor can avoid this
default behavior by explicitly invoking a superclass constructor or by invoking another
constructor of the current class with a call to this(). When a class has several constructors,
they usually apply calls to this() to collaborate with one another.


Collaboration within a Class.....................................................................................................................


The constructors of a well-designed class usually interact. Consider what happens when we
need to add a classification attribute to the Firework class so that each firework is classified
as a consumer firework or as a display-type firework. Figure 14.2 shows the Firework class
picking up firework classification constants from the ClassificationConstants
interface and adding a Classification attribute.

Free download pdf