There's one example of a use of protected where this matters in
System.Object!

The MemberwiseClone method is protected.  If derived classes were allowed to
call protected methods on instances of their base classes, then *anyone*
would be allowed to call MemberwiseClone on anything, so there would be no
point in making it protected.

It also means that you cannot accidentally do things to an instance of the
base class when you thought that you were working with an instance of the
derived class.  This can be important, because there are often a lot of
subtle and interlinked constraints between protected members.

--
Ian Griffiths
DevelopMentor


----- Original Message -----
From: "Chris Daly" <[EMAIL PROTECTED]>


> Section 3.5.3 of the C# spec lays out some restrictions on accessing
> protected members.  I don't think that Java has the analogous
> restrictions and I'm trying to figure out why they are necessary
> or desired.
>
> Basically if an object has an instance typed as its base class
> (or some class further up the inheritance chain) it cannot access
> protected members of that instance.
>
> Here's the example from the spec:
>
> public class A
> {
>    protected int x;
>    static void F(A a, B b) {
>       a.x = 1;      // Ok
>       b.x = 1;      // Ok
>    }
> }
> public class B: A
> {
>    static void F(A a, B b) {
>       a.x = 1;      // Error, must access through instance of B
>       b.x = 1;      // Ok
>    }
> }
>
> Suppose that the A we were passed in B.F was an instance of C - another
> subclass of A, like this:
>
> public class C: A
> {
>    protected new int x;
> }
>
> In this case we would still know which x to update (the one in A), right?
>
> Can anybody explain the justification for this restriction?

You can read messages from the Advanced DOTNET archive, unsubscribe from Advanced 
DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to