File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Visibility/Accessibility: illogical! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Visibility/Accessibility: illogical!" Watch "Visibility/Accessibility: illogical!" New topic
Author

Visibility/Accessibility: illogical!

Michael Herrmann
Ranch Hand

Joined: Dec 06, 2003
Posts: 60
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

Joined: Jun 23, 2005
Posts: 266
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

Joined: Dec 06, 2003
Posts: 60
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
 
 
subject: Visibility/Accessibility: illogical!