Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a private class implementing an interface keeping the implementation private

Tags:

java

Static method M returns an object implementing interface A:

interface A { ... }
static A M() { ... }

Within M I would like to construct an object of type B and return that, given that B implements A:

class B implements A { ... }

I do not want client code to know anything about how B is implemented, I would prefer for B not to be a static class, B must be immutable and there could be different B handed to different clients. I want to prevent instantiation of B outside method M at all costs (short of reflection, as one user commented).

How can I achieve the above? Where and how should I implement B? Could you please provide a short code example?

My main problem is: how can I have "different Bs?"

like image 451
Robottinosino Avatar asked Jun 30 '26 00:06

Robottinosino


1 Answers

A static inner class is probably your best bet. You won't be able to "prevent instantiation of B at all costs" since with reflection, client code can bypass all access modifiers.

like image 100
Asaph Avatar answered Jul 01 '26 13:07

Asaph