A protected member is accessible within its class and by derived class instances.
If every type in .NET derives from Object, is there any difference between a protected member and a public member in System.Object?
The protected keyword specifies access to class members in the member-list up to the next access specifier ( public or private ) or the end of the class definition. Class members declared as protected can be used only by the following: Member functions of the class that originally declared these members.
Protected members in a class are similar to private members as they cannot be accessed from outside the class. But they can be accessed by derived classes or child classes while private members cannot.
So if we want data members to be accessible to only derived classes and not privately or publicly accessible, then we can use protected. - Protected is similar to private. - It makes class member inaccessible outside the class, but the members can be accessed by any subclass of that class.
The main reason however that protected variables are not recommended is because they tend to break encapsulation. Variables and methods should have as limited visibility as possible; for further reference see Joshua Bloch's Effective Java, Item 13 - "Minimize the accessibility of classes and members".
As you said, a protected member is accessible within its class and any inheriting classes. A public member is accessible from any other class.
I see two protected members of Object
in the MSDN documentation: Finalize
and MemberwiseClone
. Those methods are callable within any inheriting classes (i.e. any class), but not publicly accessible. If we have the following:
class Foo
{
object Test()
{
return this.MemberwiseClone();
// Works, because Foo can see protected MemberwiseClone
// inherited from Object
}
}
class Bar
{
object Test()
{
var foo = new Foo();
return foo.MemberwiseClone();
// fails: Bar cannot see Foo's protected MemberwiseClone
// because Bar does not inherit from Foo
}
}
Yes
Just because you can access your "copy" of the protected member, it doesn't mean you can access another type's "copy". The following code would work with a "public" modifier.
The point in putting a protected member into Object
(provided you were able to) would be to force all objects to to have that member, without exposing it to each other.
To prove it, I wrote this code (this won't compile):
class BaseClass
{
protected bool sharedMember;
}
class DerivedClassA : BaseClass
{
public DerivedClassA()
{
DerivedClassB otherObject = new DerivedClassB();
otherObject.sharedMember = sharedMember; //Compiler error, cannot access protected member
}
}
class DerivedClassB : BaseClass
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With