class A {
private int i;
public void modifyOther(A a1) {
a1.i = 20; //1
}
}
State whether the following statement is true or false: At //1 a1.i is valid.
Answer:
True
Explanation:
Private means private to the class and not to the object. In other words, members marked private can't be accessed by code in any class other than the class in which the private member was declared.
Since i is an instance variable of class A, it means, each instance of A has its own copy of i. Even though it is declared private, Java allows you to access it from anywhere in class A if you have a valid reference to any object of class A.
In the given code, the modifyOther method is executes in context of one instance of A but is trying to access the variable i of some other instance of A. It is valid because i is not private to an instance. It is private to a class.
HTH,
Paul.
If you like our products and services, please help us by posting your review here.