Reputation: 818
I have two classes A
and B
.
How do I ensure that from no other place in my software, except from class A, is class B called or made reference to?
I thought of writing class B
inside A
but I don't particularly like that.
Can I do something like: check who called a method of class B and if it is not class A then ignore it?
Upvotes: 3
Views: 240
Reputation: 83235
The only way to restrict access is through access modifiers of some kind.
public class A {
private static class B {
}
}
But you said you didn't want a nested or inner class.
The alternative is making a separate package for the two classes, and making B
visible only to the package. (Whether this is acceptable depends on your exact situation.)
A.java
package ab;
public class A {
}
B.java
package ab;
class B {
}
Here, B
has default (sometimes also called "package private" or "package protected") visibility. It's visibility is limited to within the package.
Upvotes: 4
Reputation: 5369
If you want to restrict access to a specific client, class B should be written as an inner class (the way you don't like).
Actually, I would avoid writing a class if it is not going to exist as an independent module of functionality, called by many other modules. The only point in this would be to semantically organize data scheme.
I hope I helped!
Upvotes: 0
Reputation: 833
You can write the method you want in class B, then write a method in class A, give the instance of class B as an argumment, and call the first method from the second one, on the argument.
This is very ugly though.
Upvotes: 0