Reputation: 85
class A
{
private int aa = 1;
}
class B : A
{
private int bb = 5;
void DoStuff()
{
aa = bb; //Error, as it should
}
}
Versus:
class A
{
private int aa = 1;
class B : A
{
private int bb = 5;
void DoStuff()
{
aa = bb; //Not an error, bummer
}
}
}
Same stuff, just organized differently. I'm using the second method of organizing my classes because it looks so much cleaner to inherit inside of the class for what I'm doing. My problem is that, in the example above, I don't want A's private members to be accessable to B even though it is inside A. I'm beginning to understand that's the point of doing that systematically, but am I really forced to keep them separate if I want A's private members to be private from B?
Upvotes: 0
Views: 70
Reputation: 152556
am I really forced to keep them separate if I want A's private members to be private from B?
Yes. from the documentation
A nested type has access to all of the members that are accessible to its containing type. It can access private and protected members of the containing type, including any inherited protected members.
Also why does it matter? Since you control what goes in B
, if you don't want B
to use anything from A
then don't use it.
Upvotes: 2
Reputation: 8323
All of the other answers here are correct in mentioning that you cannot accomplish what you are trying to do, if you nest your classes rather than use separate declarations and inheritance.
One thing you should examine is the true design behind what you're doing and let that guide what design method you choose.
If you don't intend for any outside class to access Class B
and its functionality is strictly required within Class A
, then there is no way to (and no real need to) hide the members of A
from B
because B
in this case is actually a member of A
, with the same access privileges as say a method within that class.
If you plan to expose this class to other potential classes, then it's matter of design (not a matter of code cleanliness/organization) that should draw you to the first method and keep the declarations separate.
Upvotes: 0
Reputation: 51330
You can't do that.
A nested class is a class member, just like a method. All class members can see other members, even private. Just as you can see private fields from a method.
If you want to do that, it probably means your nested class shouldn't be nested in the first place.
Upvotes: 4
Reputation: 245429
Yes, you're really forced to keep the declarations separate if you don't want B
to access A
's private members because nested classes have access to their containing classes private members.
Upvotes: 6