Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question 80 from Java rules round up

 
sudha abc
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question: Can one object access a private variable of another object of the same class?
Answer: Yes.

Can someone provide me with an example to substantiate the above please?

Thanks.
 
Lakshmanan Arunachalam
Ranch Hand
Posts: 99
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I dont think so!!

private variables of an object, can't be accessed directly neither by an object of the same class nor different class. Outside world can get access to the private variables of an object using only the non-private methods of that class.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sure it's possible. We do it routinely in most equals() methods. For example:

Here other.x and other.y refer to private fields of another object of the same class.
 
sudha abc
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jim.
I find the question little confusing. Should it be rephrased as:
Question: Can an instance method of a class access a private variable of another object of the same class?

Would you agree?
 
Sasikanth Malladi
Ranch Hand
Posts: 175
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it can.
"private" means private to the CLASS, not private to the object!!
Sashi
 
Lakshmanan Arunachalam
Ranch Hand
Posts: 99
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all !

Now I got it.
 
Purujit Saha
Ranch Hand
Posts: 86
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Aprivate
{
private int i=0;

public Aprivate(int i)
{
this.i=i;
}

void m(Aprivate a)
{
System.out.println(a.i);
}

public static void main(String args[])
{
Aprivate a1=new Aprivate(12);
Aprivate a2=new Aprivate(10);
a2.m(a1);

}
}
 
Karthikeyan Balasubramanian
Ranch Hand
Posts: 89
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hii sudha.....

Keep in mind that access refers to the inherited access..mostly..

If a class is able ti inherit a method of it's super class ,it means the subclass has the access to the method of the superclass.

tat's K&B says....
 
Karthikeyan Balasubramanian
Ranch Hand
Posts: 89
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And the solution to ur question is......it is possible if the objects created are in the same class.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic