Java Reference
In-Depth Information
CHALLENGE 13.4
How can you use the visibility of the Chemical_1 class to discourage other
developers from instantiating Chemical_1 objects?
Visibility modifiers do not supply the complete control over instantiation that you might want.
You might like to ensure that ChemicalFactory is absolutely the only class that can create
new Chemical instances. To achieve this level of control, you can apply an inner class,
defining the Chemical class within ChemicalFactory . Java™ in a Nutshell (Flanagan
1999b) has a good description of the various types of inner classes that Java provides.
For ChemicalFactory , you can declare Chemical as a static member class. This
indicates that Chemical need not reference any instance variables in ChemicalFactory .
You might want to name the inner class ChemicalImpl and use the name Chemical for an
interface. This lets clients refer to Chemical objects rather than
ChemicalFactory.Chemical objects. Clients will never reference the inner class
directly, so you can make it private, ensuring that only ChemicalFactory has access to it:
package com.oozinoz.chemical;
import java.util.*;
public class ChemicalFactory
{
private static Map chemicals = new HashMap();
static
{
chemicals.put(
"carbon",
new ChemicalImpl("Carbon", "C", 12));
//...these puts are all here, but elided for space
}
private static class ChemicalImpl implements Chemical
{
?? (declare instance variables) ??
private ChemicalImpl( ?? )
{
??
}
public double getMoles(double grams)
{
return ??
}
public String getName()
{
return name;
}
public String getSymbol()
{
return symbol;
}
Search WWH ::




Custom Search