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.
Thanks for your first contribution to this forum and...
Welcome to the Ranch!
Hope you'll enjoy.
Only one small issue: The Java Ranch follows a certain policy regarding user names. The main reasons why and a link how to change yours you'll find here: http://www.javaranch.com/name.jsp
So, could you please change your user name before your next posting? It will not affect anything you've already posted here. Just your user name will update.
I'm posting this because I am one of the moderators of this forum.
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.