Wednesday 10 October 2012

Anonymous inner class

Here is an interface


public interface Factory {
    public Object getObject();
}


Here is the client code


public class Client {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Client client = new Client();
        Factory f = client.createFactory("abc");
        print(f);
    }
 
 
    private Factory createFactory(Object obj){
        //TODO
        return null;
    }
 
    private static void print(Factory factory){
        System.out.println(factory.getObject());
    }
}


How will you go about coding the createFactory(Object obj) method so that print(f) will yield the result "abc"?

The traditional approach is to create an implementation of Factory interface.

class FactoryImpl implements Factory{

    private Object o;
 
    public FactoryImpl(Object o) {
        super();
        this.o = o;
    }

    public Object getObject() {
        return o;
    }
 
}


Then create an instance of FactoryImpl

private Factory createFactory(Object obj){
    Factory factory = new FactoryImpl(obj);
    return factory;
}


The task gets much easier if we use anonymous inner class

No need to create a named class that implements the Factory interface. Instead...

private Factory createFactory(final Object obj){
    Factory factory = new Factory() {
        public Object getObject() {
            return obj;
        }
    };
    return factory;
}


There is one caveat: The argument obj must be declared as final. Or it doesn't compile.