jipthechip
jipthechip

Reputation: 177

Having an Interface provide an instance of a Class that implements it

If I have the interface:

public interface Val {
    public NilVal NIL;
}

And a singleton class that implements it:

public class NilVal implements Val {

    private static NilVal nil = null;

    private NilVal() {
    }

    public static NilVal getInstance(){
        if(nil == null)
            nil = new NilVal();
        return nil;
    }
}

How would I go about instantiating NIL as a NilVal object in the interface?

Upvotes: 1

Views: 36

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533530

You can do

public interface Val {
    Val NIL = NilVal.getInstance();
}

However you could also do

public interface Val {
    Val NIL = new NilVal();

    class NilVal implements Val {
        private NilVal() { }
    }
}

or even

public interface Val {
    Val NIL = NilVal.NIL;

    public enum NilVal implements Val { NIL }
}

Upvotes: 2

Related Questions