Tim Vernum
Posts: 58
Nickname: tpv
Registered: Dec, 2002
|
|
Re: Can't access protected members of base class
|
Posted: Nov 9, 2003 6:02 PM
|
|
> ....so, it appears that I have to create a public method > in B that accesses i or j if I want to be able to alter > them in Class Prog. It doesn't make sense to me that I can > access A's protected data from within B's methods, but I > can't access A's protected data by creating an instance of > B, then using B.i or B.j in the class that created B.
That is the whole point of protected.
The behaviour you're seeing is the exact reason why protected exists. In order to understand why having a feature like that is useful, you need to come to an understanding of "information hiding".
Assume we have class Foo
Let's start with a field declared as public int x ;
. That says any piece of code in your whole program can access "x" if it has an instance of Foo to get at. So,foo.x = 1 ;
is always valid code.
Now let's jump to the other end of the scale and talk about private int z ;
. That says that only code within Foo can access "z". So,foo.z = 1 ;
is only valid code inside Foo directly. No other class can have this code, or you'll get a compile error.
So, then we have protected int y ;
. That says that "y" can be accessed from inside Foo, it can be accessed from inside any class the extends Foo, but not from anywhere else. So,foo.y = 1 ;
is only valid code inside a class that is either Foo , or is extended from Foo . If a class does not extend Foo, then it is not allowed to get access to "y". Ever.
In your example you expected that you'd be able to access "i" on class "B" because "B" is derived from "A". But that's a misunderstanding of what the access controls mean. They aren't about controlling which objects can be accessed, they're about controlling which classes can perform the access.
So the fact that B is derived from A doesn't mean that Prog can now get at the protected data in B . Rather it means that now B can get at the protected data.
The short of it is: Whether you can access protected fields is determined by who you are relative to the object being accessed, not just by the type of the object being accessed..
|
|