Archived

This topic is now archived and is closed to further replies.

[java] Strange Method Access Privilege

This topic is 5506 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This is strange, its not a problem but I am wondering if it is a bug of some sort. I have a class with a protected method inside like: class c1 { protected int m1() {...} } Now I have another class derived from this one. class c2 extends c1 { ... } The thing is now I can create an instance of c2 and do this: c2 v = new c2(); int n = c2.m1(); Now, this shouldn''t be happening cause m1 is protected and not public. Is my knowledge in Java wrong or is this a bug? Have anyone come across this problem?

Share this post


Link to post
Share on other sites
As I recall, Java''s keyword protected allows access from derived classes and from any class or method in the same package (unlike in C++, where it is only for derived classes).

Share this post


Link to post
Share on other sites
It''s not a bug at all.. the whole point of having a protected methods and fields is to allow them to be accessed by descendant classes and classes in the same package.

Your protected method won''t be accessable by other classes.

If you want your methods not to be accessed by any other class then you''ll want to define that method as "private".



Share this post


Link to post
Share on other sites
I see, thanks for that I didnt know.
I guess I have to start sorting out my applications as packages instead of just placing them in the same place. I always thought protected would just allow derived classes not outside classes in the same package.

Share this post


Link to post
Share on other sites