Stack

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.

Factory/Java Source

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();
}
}

Test Program

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.

package test;

class StackTest {
    public static void main(String argv[]) {
        <let> <var> T </var>
        <apply>
            <factory> examples/Stack </factory>
            <args> <const> test.Person </const> </args>
        </apply>
        <body>
            <var> T </var> p = new <var> T </var>();
       
            p.push(new Person());
            p.pop();
       
            // causes type error
            // p.push(new Object());
        </body> </let>
    }
}

This factory can be compiled in the factory directory with
java -classpath classes factory.Factory -javad src -classd classes src/test/StackTest
and run with
java -classpath classes test.StackTest