File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Private member accessible to other Objects.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Private member accessible to other Objects.." Watch "Private member accessible to other Objects.." New topic

Private member accessible to other Objects..

Ismael Upright
Ranch Hand

Joined: Feb 15, 2007
Posts: 166

Consider the following code:

This way one Object of class A can modify private member of another Object of class A.

Don't you think that it's a strange rule in Java?

I would rather expect that private member is private to all Objects... If I would make class Person and private member named bankAccountNumber... Why other Objects of class Person should be able to read something that is private to them??

Why Java creators have decided to do something like that?
Stevi Deter
Ranch Hand

Joined: Mar 22, 2008
Posts: 265


Per the Java Language Specification,

A private class member or constructor is accessible only within the body of the top level class (�7.6) that encloses the declaration of the member or constructor.

In your example, a1 is defined in the body of the top level class, so it's accessible in class A's method modifyOther.

This is why we can write equals() classes that include statements like

Writing proper clone methods could be very painful and overly verbose if you couldn't access private member variables.

Think of it this way - Object A knows all about how it's implemented. Why pretend that it doesn't? It's up to you as the programmer to decide that if A instance a1 and A instance a2 can muck with each other directly through proper encapsulation.

There will always be people who are ahead of the curve, and people who are behind the curve. But knowledge moves the curve. --Bill James
I agree. Here's the link:
subject: Private member accessible to other Objects..
jQuery in Action, 3rd edition