Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Visibility/Accessibility: illogical!

 
Michael Herrmann
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following classes:




Compiling B results in an error:
"The field name is not visible" on the line
System.out.println(b.getThis().name);
->
System.out.println(b.name);
compiles fine, although it is essentially the same.

If A and B are in the same package, the code compiles fine (B seems to be accessing name as a package member, not as a subclass), the same with name being public.

Why is this? This seems totally illogical to me. I can't believe this could be a bug.

Thanks for any reply
 
Satish Chilukuri
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is not a bug. It is a tricky case of access control.
When you are saying



you are accessing a private instance variable inside a method which is perfectly legal.

But when you say



you are obtaining a refernce of type A and trying a access its instance variable which in effect is private to B (because they are in different packages). It is equivalent to saying



Remember that protected members are accessible only through inheritance outside the package. What you are trying to do is to access them directly.

The code works fine when both classes are in same package as you can access a protected member outside the class within the same package.

Hope this helps.
 
Michael Herrmann
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much, Satish.
My explanation (which repeats yours but seems clearer to me) is: If getThis returns an object of type A, one can't know whether this object secretly is of type B. B only has access if this is the case.

-> Changing getThis to the following removes the error:


If B had access to the protected fields of any A it could modify protected fields of other subclasses of A.

Thanks again
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic