Stack is a factory implementation of a generic stack class. It demonstrates parametric polymorphism (also known as generic types). For an actual type parameter Person this factory generates a class PersonStack with push() and pop() methods that have their types adjusted to Person, so that the Java compiler can ensure at compile-time that the stack is only used with objects compatible to Person.
The source can be found in the Factory/Java .zip-archive in factory/classes/examples/Stack.factory:
<param> <var> T </var> </param>
package test;
import java.util.Stack;
public class
<apply>
<apply>
<class> factory.Toolbox </class>
<method> getRelativeName </method>
<args>
<var> T </var>
</args>
</apply>
<method> concat </method>
<args>
<const> "Stack" </const>
</args>
</apply>
{
Stack s = new Stack();
public void push(<var> T </var> value) {
s.push(value);
}
public <var> T </var> pop() {
return (<var> T </var>) s.pop();
}
}
The following unparameterized factory
can be found in factory/src/test/StackTest.factory in the
Factory/Java .zip-archive. It applies factory Stack to
class Person, instantiates an object
of the resulting class PersonStack and uses it with a Person
object.
If we uncomment the line of Java code
that tries to push an instance of class Object onto the PersonStack,
we will not be able to compile it, because the type-checker refuses the push()
method used with an object incompatible to Person.
java -classpath classes factory.Factory -javad src -classd classes src/test/StackTestand run with
java -classpath classes test.StackTest