Two Laptop Bag*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes can 2 objects of the same class acess private data of each other? 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 "can 2 objects of the same class acess private data of each other?" Watch "can 2 objects of the same class acess private data of each other?" New topic
Author

can 2 objects of the same class acess private data of each other?

Seema Ahuja
Ranch Hand

Joined: Feb 01, 2006
Posts: 32
guys another question:

i want to know how an object of a class can access the variable of another object of the same class?
i get stack overflow error when i compile the following program:



Also if i delare both the objects in the main...there is no way i can access the 2nd object with the refrence of the 1st.
what i mean is:


can anyone pl tell me is there any way we can acess the object of the same class with out declaring it as static within that class.
jeancarlo sott
Greenhorn

Joined: Jan 12, 2005
Posts: 8
Hi,

I'm getting the error stackoverflowerror in this case too:



The instantiation cannot be on the class scope or in an contructor.

Hope someone can clarify bether.


That the java be with you.<br />SCJP 5.0<br />SCJD: in progress
Edisandro Bessa
Ranch Hand

Joined: Jan 19, 2006
Posts: 584
Dear Seema,

Both code fragments can compile and both raises StackOverFlowError just because when you create and instance the JVM automatically creates another instance to assign to inc member and so on. The program enters in a infinite recursive calls.

I think you are trying to do something like a list where a node points to another node and so on.

So, I belive the code below would be suitable for you.



"If someone asks you to do something you don't know how to, don't tell I don't know, tell I can learn instead." - Myself
Abhinav Gogna
Greenhorn

Joined: Oct 23, 2005
Posts: 20
Can't you just put that as an Instance variable instead of defining in the initializer block.

For eg:

class abc{
private int 1; // ----> is accessible by all the methods within the class only.
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

jeancarlo, please click on the My Profile link above and add a space between your first and last name.

Thanks

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023

Yeap. You can.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: can 2 objects of the same class acess private data of each other?
 
Similar Threads
doubt pass by copy
Doubt with ++ operator
What is the output
Private Access Q
Passing Value