permaculture playing cards
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes JavaRanch Rule Round-up Game Query ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "JavaRanch Rule Round-up Game Query ??" Watch "JavaRanch Rule Round-up Game Query ??" New topic

JavaRanch Rule Round-up Game Query ??

Jay Pawar
Ranch Hand

Joined: Aug 27, 2004
Posts: 411
I came across this question on Ranch Roundup Game as shown below

Can one object access private variable of another object of the same class ?
a) Yes
b) No

The answer is Yes.
The explanation given is: Private means "private to the class", NOT "private to the object" . So two objects of the same class could access each others private data.
My interpretation for the above question was as follows

public class Employee {
private int salary;
public static void main (String [] args){
Employee emp1 = new Employee();
emp1.salary = 1000;
Employee emp2 = new Employee();
/*How can one write a code here using emp2 object and modify the emp1.salary which is private data of object emp1.*/

May be my interpretation of the question is wrong ? Gurus help me !!!


Cheers,<br />Jay<br /> <br />(SCJP 1.4)<br />Heights of great men were not achieved in one day, they were toiling day and night while their companions slept.
Joel Ricker

Joined: Mar 31, 2004
Posts: 17
I think it means something like this:

Here since emp1 and emp2 are both Employee objects, they both have access to each other's salary attribute. If this sort of behavior was not allowed, then we would need to provide getter methods for all private variables if we needed to share information between objects of the same class. This way we do not expose the fact that Employee objects even have a salary attribute.

Hope this helps,
[ September 02, 2004: Message edited by: Joel Ricker ]
Jessica Sant

Joined: Oct 17, 2001
Posts: 4313

your intepretation of the question was on the right path.

You just had to give the Employee class an instance method that will modify the other objects private variables.

Like this:

So the result is:
E:\blah>java Employee
Jess makes $1000
Jay makes $2000
emp1 modifies emp2:
Jess makes $1000
Mud makes $3333

(ha ha, your name is now "Mud" -- but don't worry, cause at least I gave you a raise )
[ September 02, 2004: Message edited by: Jessica Sant ]

- Jess
Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
Jay Pawar
Ranch Hand

Joined: Aug 27, 2004
Posts: 411
Thanks a lot Joel and Jessica.
I liked the salary hike, wish you were my manager.
I agree. Here's the link:
subject: JavaRanch Rule Round-up Game Query ??
It's not a secret anymore!