This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
It is not clear from your statement "how to get the answer as 15 for this code", what exactly are you looking for. Your code already gives the answer as 15 on running it. Why at all do you need to do any changes in that for getting answer as 15?
The flow of current code is as follows: 1. An object of type AClass is created in heap and is assigned to reference 'ref1'. This object will have its internal state as 5. 2. Another object of type AClass is created and is assigned to reference 'ref2'. This object will have its internal state as 10. 3. A copy of 'ref2' will be created and will be given the name 'ref'. Thus AClass object with state 10 shall have two references viz., 'ref2' and 'ref'. 4. The add method of AClass object with state 5 will be called by passing it the copied reference 'ref'. 5. The add method will add the AClass object (with state 5) x value with that of AClass object (with state 10) x value and return it. 6. This value (15) shall be printed on console.
Originally posted by Mohammad Hossain: How would you get access to the private member x. You need a public method, or you need to make the variable public.
Private does not mean private to the instance. It is private to the class. This means that an instance can actually access the private member of another instance, provided that both instances are of the same class type.