It's not a secret anymore!
The moose likes Beginning Java and the fly likes instantiation again Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "instantiation again" Watch "instantiation again" New topic

instantiation again

Nazma Panjwani

Joined: Jan 17, 2010
Posts: 17
ok guys,

So Mammal human =new Mammal, what if I create another variable that points to the same object as human....So Mammal person; Now I don't want to just simply assign it like person = human, because the person will just copy the reference. Since human refers to some memory space that is storing a reference to this Mammal object, I want person variable to to refer to the same memory space that human is referring to. So basically, I want person to refer to the original reference, not simply store a copy of the reference. Because if human and person both refer to the original reference, by making one of them point to a new object , ex. person = female (female is pointing to some Mammal object), human should also point to the object that female is pointing at, which wouldnt be possible if person was just storing a copy of the reference, in which case person will point to a new object but human will point to the original object.
I hope I am clear enough....
W. Joe Smith
Ranch Hand

Joined: Feb 10, 2009
Posts: 710
I'm slightly confused, but let me see if I can answer.

If you assign human by doing human = person, they both have their own references to the same object. I don't know of a way for you to have person point to a different object and automatically have human point to it too, since person and human each hold their own reference to the mammal object, and when you reassign person it has no affect(effect?) on human. Perhaps someone else has an idea, but the best I can come up with is having a method that is called to set person to a new reference that then sets human to the same reference as person.

Why do you want this functionality? Maybe if you explain the thought process we can come up with a better solution.

When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."
marc weber

Joined: Aug 31, 2004
Posts: 11343

I think what you're describing requires direct access to pointers, which Java does not support.

What exactly are you trying to accomplish? If "person" should reference whatever object "human" is referencing (even when human is reassigned to point to a different instance), then what is the reason for having a separate variable, "person"? Why not just use "human"?

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link:
subject: instantiation again
It's not a secret anymore!