Just for the sake of example I am putting in String as member variable. But there is complex structure originally.
public class ClassA {
private final String test ;
public ClassA(String str) {
test = str;
}
@Override public int hashCode() {
return test.hashCode();
}
@Override public boolean equals(Object obj) {
return obj instanceof ClassA && test.equals(((ClassA)obj).test);
}
}
public class ClassB {
public static void main(String args[])
{
ClassA obj1 = new ClassA("abc");
ClassA obj2 = new ClassA("def");
obj1.equals(obj2);
obj2.test;//not valid
}
}
From what I know access to the private variable test
of obj1
is there only within the methods of ClassA and these methods should be called from the context of obj1
.
When I called obj1.equals(obj2)
test variable of obj2 is accessible from the obj1's context.
So can we access the private variables of any object of type ClassA from within ClassA methods.