-2

someObj.java


public class someObj {
        private int data;

        someObj(int initVal) {
            data = initVal;
        }
        int getAnotherObjectData(someObj bar) {
            return bar.data;
        } 
}

Tester.java

    someObj foo = new someObj(30);
    someObj bar = new someObj(40);
    System.out.println(bar.getAnotherObjectData(foo));

In result, I can get '30'. Why I can access another Object's private variable data?

fatCop
  • 2,556
  • 10
  • 35
  • 57
ynifamily3
  • 17
  • 4

1 Answers1

2

As it's the same class implementation, it means that you are writing this class by yourself, so you can control it 100%. So it's not a problem if you can access other objects of the same type as well. Such feature can be useful when implementing equals or clone methods like this:

public class MyObj {
    private int a;
    private long b;

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        MyObj other = (MyObj) obj;
        if (a != other.a)
            return false;
        if (b != other.b)
            return false;
        return true;
    }
}

Without field access for proper equals implementation you would need to have non-private getters for all fields which may be not desired in many cases.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334