Hi,
If yes how? Is encapsulation implemented only using modifiers and interface(if i am not wrong)??? What else can be done to implement encapsulation?
Thanks
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Kavita BPosted Apr 6, 2011, 12:13 PM
VulpesPosted Mar 29, 2011, 4:42 AM
The following compiles and works fine:
However, this only works because the derived class N2 is also nested within A and is therefore within the same scope as N. It's difficult to see why anyone would want to do this in practice but it's a good answer to an interview question ;)
VulpesPosted Mar 28, 2011, 5:20 AM
'Top level' classes are either internal (by default) or public.
So, this is OK:
class A // internal if no modifier
{
public int MemberA; // accessible only within current assembly
private Class N // not accessible outside A
{
public int MemberN; // not accessible outside A
}
}
class B : A
{
// can't access A.N
}
As Shirsendu said, private classes can't be inherited but the enclosing class can be (unless it's sealed).
Accessibility to members of a class (strictly speaking a nested class is a static member) is controlled by the access modifier which (in C#) can be public, protected internal, internal, protected or private. If you don't use a modifier, then a member is private by default.
However, a member's accessibility may be limited by the accessibility of the class itself because a member cannot be more accessible than its class. So, for example, if you declare public members of an internal class, then those members will also effectively be internal. Similarly, if you declare public members of a private class, then those members (like the nested class itself) will not be accessible outside the enclosing class.
If a class implements an interface, then all the implemented members must be declared public. The only exception to this is where a member is implemented explicitly:
IFace
{
void MethodI(); // access modifier not allowed but implicitly public
void MethodE(); // ditto
}
class C : IFace
{
public void MethodI(){} // public needed here
void IFace.MethodE(){} // implemented explicitly so no access modifier allowed
}
The only way to access IFace.MethodE is through an IFace reference:
C c = new C();
c.MethodI(); // OK
c.MethodE(); // not allowed
((IFace)c).MethodE(); // OK
So in a sense IFace.MethodE() is both public and private :)
Shirsendu NandiPosted Mar 28, 2011, 2:18 AM