Restricting Class Access

K

knightowl

I am not sure if there is a way to do this, but here goes...

I have Class A, Class B, and Class C all which are stand alone objects.
Now I want Class D to be the only class that can create an instance of
A, b, or c.
 
A

Andrey Kuznetsov

I am not sure if there is a way to do this, but here goes...
I have Class A, Class B, and Class C all which are stand alone objects.
Now I want Class D to be the only class that can create an instance of
A, b, or c.

put them all in same package and make only class D public.
 
A

Andrew McDonagh

knightowl said:
I am not sure if there is a way to do this, but here goes...

I have Class A, Class B, and Class C all which are stand alone objects.
Now I want Class D to be the only class that can create an instance of
A, b, or c.

Make 3 interfaces A, B & C and implement them as package private i.e.
remove the 'public' keyword from them :

class Aimpl implements A {
...
}

class Bimpl implements B {
...
}

class Cimpl implements C {
...
}

Then have apublic Factory class that creates the instances of A,B & C
for everyone.

So your code that makes use of the 3 classes would be :

factory.createA(...);
factory.createB(...);
factory.createC(...);

Take a look at ...

http://industriallogic.com/xp/refactoring/classesWithFactory.html

This example assumes that the 3 classes are of the same type, but the
same pattern works with unrelated types as above.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top