Page 1 of 1

About Question enthuware.ocpjp.v8.2.1469 :

Posted: Sat Jan 23, 2016 11:01 am
by vonvon
I don't understand the explanation of the answer of this question:
Question:
Consider this class:

Code: Select all

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.

Re: About Question enthuware.ocpjp.v8.2.1469 :

Posted: Sat Jan 23, 2016 11:31 am
by admin
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.

Re: About Question enthuware.ocpjp.v8.2.1469 :

Posted: Sat Jan 23, 2016 11:37 am
by vonvon
Now, it's really clear. Thank you very much.