aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question 80 from Java rules round up 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 "Question 80 from Java rules round up" Watch "Question 80 from Java rules round up" New topic
Author

Question 80 from Java rules round up

sudha abc
Greenhorn

Joined: Dec 07, 2005
Posts: 3
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

Joined: Nov 02, 2005
Posts: 99
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.


Regards<br />Lakshmanan<br />IBM-OOAD & UML, SCEA-I
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
sudha abc
Greenhorn

Joined: Dec 07, 2005
Posts: 3
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

Joined: Nov 04, 2000
Posts: 175
Yes, it can.
"private" means private to the CLASS, not private to the object!!
Sashi
Lakshmanan Arunachalam
Ranch Hand

Joined: Nov 02, 2005
Posts: 99
Thanks to all !

Now I got it.
Purujit Saha
Ranch Hand

Joined: Nov 01, 2005
Posts: 86
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

Joined: Apr 20, 2005
Posts: 89
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....


SCJP 1.4--93%<br />SCWCD 1.4--86%<br />Next--???
Karthikeyan Balasubramanian
Ranch Hand

Joined: Apr 20, 2005
Posts: 89
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
 
subject: Question 80 from Java rules round up