Access private field of another object in same class
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Java, a private field is private to the class, not private to one particular instance. That means code inside a class can access the private fields of any other instance of the same class.
This surprises people who read private as "only this object may see the field." Java does not define access that way. Access control is based on the declaring class.
What private Actually Means
When a field is declared private, only code written inside the same top-level class can access it directly. That rule applies whether the code is reading this.value or other.value.
A small example makes it clear:
Both hasMoreMoneyThan and transferTo access other.balance directly, and that is valid Java because the access happens inside the Account class.
Why The Language Allows This
Java's access modifiers are designed around encapsulating implementation details at the class boundary. If code in the same class could not access private fields of peer instances, common patterns such as copy constructors, equality checks, merges, and internal comparisons would become awkward.
For example, a copy constructor often needs to read private state from another instance:
That is still fully encapsulated because the access remains inside Point.
Equality And Comparison
Another common use case is implementing equals or helper comparison methods:
Direct access to other.id and other.email is both legal and idiomatic because the code is part of the same class.
What Is Still Forbidden
Code outside the class cannot access those private fields directly, even if it has another instance of the class:
That line fails because Demo is outside the Account class.
Common Pitfalls
The most common mistake is assuming privacy is instance-based rather than class-based. In Java, the access rule is tied to where the code is written, not which object the field belongs to.
Another pitfall is exposing getters only because developers think internal peer access is impossible. If the only reason for a getter is letting one instance read another instance's state inside the same class, that getter may be unnecessary.
A third issue is confusing Java with languages that enforce privacy differently. The exact rule varies across languages, so this behavior should not be assumed outside Java and similar class-based systems.
Summary
- In Java,
privatemeans private to the declaring class. - Methods inside a class can read and write private fields on other instances of the same class.
- This behavior supports copy constructors, comparisons, and internal state transfer.
- Code outside the class still cannot access those fields directly.
- The key idea is class-level encapsulation, not per-instance encapsulation.

