Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying private instance variables in Java [duplicate]

Tags:

java

So, I came across an example in a 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 is passed with another Account object to check if all instance variables are equal. My problem with this piece of code is that it seems as thought we're directly accessing private variables in the anotherAcc object, which doesn't seem right, but it works. The same thing happens when I make a main method in the same class where I somehow gain access to the private variables.

Conversely, when I create a main method in another class, it's only then I get a visibility error. My question is, why does Java allow private instance variable to be accessed in a object that is passed in a method? Is it because the object is of type Account and the method being passed to is part of a class called Account?

like image 510
Dimitri Avatar asked Nov 23 '14 15:11

Dimitri


1 Answers

See (my favorite table) 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

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

As mentioned in the comments, note that you're not overriding the correct equals method. The original one (of Object class), expects an object of type Object as an argument.

like image 174
Maroun Avatar answered Oct 05 '22 08:10

Maroun