Changing private instance variables in Java

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 ?

+6
source share
3 answers

See (my favorite table) Access control for class members :

 Modifier Class Package Subclass World ------------------------------------------- public YYYY protected YYYN no modifier YYNN private YNNN ↑ You are here 

Since you are in the same class, private members are available.

As mentioned in the comments, note that you are not overriding the correct equals method. The source (from the Object class) expects an object of type Object as an argument.

+9
source

Is it because the object is of type Account and the method passed is part of the Account class?

Yes , private means not only this object, but also any object belonging to the same class .

+3
source

private restricts access to the code in the same class, and not just in the same instance.

+2
source

Source: https://habr.com/ru/post/978579/


All Articles