Q:

Java code for composition

Is it possible to implement composition in Java?
If we create a class A and use an instance of this class in class B, then how can we ensure that A cannot create an independent object by itself?

A:

I do not think it is possible. The only similar solution is to create A as private inner class of B. Then nobody else than B can instantiate A.

