This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Private member accessible to other Objects.." Watch "Private member accessible to other Objects.." New topic
Author

Private member accessible to other Objects..

Ismael Upright
Ranch Hand

Joined: Feb 15, 2007
Posts: 166
Hiho,

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

Ismael,

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: http://aspose.com/file-tools
 
subject: Private member accessible to other Objects..
 
Similar Threads
Accessing private variables directly from outside the class
Help on private access
ExamLab - garbage collection (3rd test, question no. 19)
Is it not against OO concept?
One basic question