• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Private member accessible to other Objects..

 
Ismael Upright
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic