• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JavaRanch Rule Round-up Game Query ??

 
Jay Pawar
Ranch Hand
Posts: 411
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
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
Jay
 
Joel Ricker
Greenhorn
Posts: 17
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
Joel
[ September 02, 2004: Message edited by: Joel Ricker ]
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jay Pawar
Ranch Hand
Posts: 411
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Joel and Jessica.
I liked the salary hike, wish you were my manager.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic