/** * Java and Object Closures. * Although Java does not have closure, you can get something very similar * using interfaces and creation of classes that implement interface within * a function. For instance, how is the below much different from a the * incrementer closure in Go from homework 3?? * * @author gtowell * Created: Nov 20, 2022 gtowell */ public class ObjClo { /** * the interface that the ObjectClosure will implement. * Usually this would be a common, well-defined interface * but for this purpose a private one-off will do. */ private interface Funcer { int doFunc(int val); } /** * A function that returns an object closure. * @param val * @return an instance of a class that implements Funcer */ public Funcer makeIncrementer(final int val) { // define a new class!! within this function. final class IFuncer implements Funcer { private int jj = 0; // count the number of calls /** * The incrementer "closure" */ public int doFunc(int vv) { return (jj++) * val; } } //val=val+10; // This causes the compiler to barf!! return new IFuncer(); } public static void main(String[] args) { (new ObjClo()).doo(); } /** * Example! */ public void doo() { Funcer ff = makeIncrementer(7); System.out.println(ff.doFunc(0)); System.out.println(ff.doFunc(0)); System.out.println(ff.doFunc(0)); System.out.println(ff.doFunc(0)); } }