Are Private Variables Truly Private?
Background
When I was just beginning my programming career, I was interviewing with a company for a new grad role. During that interview, I was asked the question - can private variables of a class be accessed by other objects?
I thought the answer was obvious, Of course not - this goes against the whole principle of encapsulation!
class Example {
private int secretValue;
public Example(int value) {
this.secretValue = value;
}
public int getSecretValue() {
return this.secretValue;
}
}
Example example = new Example(42);
In the above example, secretValue is surely not accessible by anything other than example right?
(Of course we are ignoring the escape hatch of reflection that is present in basically every language with the private modifier)
That was exactly what I thought and I responded with a "No", explaining my above thought process using encapsulation.
Then the interviewer asked me what happens in the equals method?
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Example other = (Example) obj;
return this.secretValue == other.secretValue;
// Accessing private variable of another object!
}
How could I forget this - a method inherited by every Java object!
I had probably used it dozens of times without ever realizing that I was accessing private variables of another object!
Well, you live and you learn. Thankfully, the interviewer saw something in me despite my incorrect answer, and I was still able to get an offer!
What are "private" variables?
Below is a definition of encapsulation from wikipedia:
In software systems, encapsulation refers to the bundling of data with the mechanisms or methods that operate on the data. It may also refer to the limiting of direct access to some of that data, such as an object's components.
This makes it seem like private variables are only accessible within their own object! Yet based on the above example it is absolutely clear.
Private variables are private to the class -- not the object!
The Oracle Java documentation states this clearly:
A class always has access to its own members
Author's Note
This seems like a very basic detail, but you would be surprised by how many people (including myself) get this wrong!
Hope you enjoyed this quick read! I kept things very simple and short for my first blog post.