public class Demo { public static void main(String[] args){ Tree sampleTree = new Tree("dog", new Tree("bat", null, new Tree("camel", null, null)), new Tree("mouse", null, null)); // The outermost procedure has a static link pointing at a frame // containing any global variables. GlobalFrame globals = new GlobalFrame(); String result = new PrettyprintFrame(globals).prettyprint(sampleTree); System.out.println(result); } } class Tree { String key; Tree left, right; Tree(String key, Tree left, Tree right){ this.key = key; this.left = left; this.right = right; } } class GlobalFrame { // any globals would go in here; Program 6.3 has none } class PrettyprintFrame { GlobalFrame staticLink; String output; // this is the one escaping variable PrettyprintFrame(GlobalFrame staticLink){ this.staticLink = staticLink; } String prettyprint(Tree tree){ output = ""; new ShowFrame(this).show(0, tree); return output; } } class WriteFrame { PrettyprintFrame staticLink; // no escaping variables WriteFrame(PrettyprintFrame staticLink){ this.staticLink = staticLink; } void write(String s){ staticLink.output = staticLink.output + s; } } class ShowFrame { PrettyprintFrame staticLink; int n; // escaping variable ShowFrame(PrettyprintFrame staticLink){ this.staticLink = staticLink; } void show(int nArg, Tree t){ n = nArg; // store in frame since it escapes if(t == null){ new IndentFrame(this).indent("."); } else { new IndentFrame(this).indent(t.key); new ShowFrame(staticLink).show(n+1, t.left); new ShowFrame(staticLink).show(n+1, t.right); } } } class IndentFrame { ShowFrame staticLink; // no escaping variables IndentFrame(ShowFrame staticLink){ this.staticLink = staticLink; } void indent(String s){ for(int i = 1; i <= staticLink.n; i++){ new WriteFrame(staticLink.staticLink).write(" "); } staticLink.staticLink.output = staticLink.staticLink.output + s; new WriteFrame(staticLink.staticLink).write("\n"); } }