So, I found an example in the Java book I found:
public class Account { private String name; private double balance; private int acctNumber; public Account(){} public boolean equals(Account anotherAcc) { return (this.name.equals(anotherAcc.name) && (this.balance == anotherAcc.balance) && (this.acctNumber == anotherAcc.acctNumber)); } }
We see that the equals method is overloaded and passed by another Account object to check if all instance variables are equal. My problem with this piece of code is that it seems like we are directly accessing private variables in anotherAcc object, which seems to be wrong, but it works. The same thing happens when I make the main method in the same class, where I somehow access the private variables.
And vice versa, when I create the main method in another class, only then I get a visibility error. My question is: why does Java allow access to the private instance variable in the object that is passed in the method? Is it because the object is of type Account , and the method passed is part of a class called Account ?
source share