Modifying private instance variables in Java
See English answers > java private field visibility6
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 the equals method overloaded and passed with another account object to check that all instance variables are equal My problem with this code is that we think it's wrong for us to directly access private variables in another object, but it does work When I create a main method in the same class, I access private variables in some way
On the contrary, a visibility error occurs when I create a main method in another class My question is, why does Java allow access to private instance variables in objects passed in methods? Is it because the object is of type account and the method passed to is part of a class named account?
Solution
Controlling access to members of a class:
Modifier Class Package Subclass World ------------------------------------------- public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N ↑ You are here
As you are in the same class, private members are available
As stated in the comments, please note that you did not override the correct equals method The original (object class) expects an object of type object as a parameter