Reputation: 5849
I am trying to learn Java.
I have a custom class, which has attributes:
public class Person{
private String name;
}
I have another class, where I do:
public class foo{
private Person guy;
public void setGuy(Person guy){
this.guy = guy;
}
public Person getGuy(){
return guy;
}
void someMethod(){
Person anotherGuy = new Person();
anotherGuy = getGuy();
}
}
I am confused when I use the getGuy()
method.
I thought that when I do this:
Person anotherGuy = new Person();
anotherGuy = getGuy();
I create a new object, which has the same value as guy. But it seems that anotherGuy is actually a pointer to guy. So
Person anotherGuy = getGuy();
and the above 2 lines, do the exact same thing? I am confused. Also then how do I create a entirely new object in memory?
Upvotes: 0
Views: 321
Reputation: 46137
While folks have already talked/explained about the behavior of your existing code, in order to do what you want to, use the clone
feature in Java, wherein your Person class would implement the Cloneable
interface, which would ask you to implement the clone()
method.
Your clone()
method should like this :
public Object clone()
{
Person p = new Person();
p.setName(this.name);
// similarly copy any other properties you want
return p;
}
and then invoke clone to copy your object:
Person another = (Person) person.clone();
Upvotes: 1
Reputation: 2112
Yes, both do the same thing, in that after both method calls, anotherGuy == null
.
Upvotes: 0
Reputation: 2348
Person anotherGuy;
this is a reference to a Person object
anotherGuy = new Person();
this sets the reference to a new Person object
anotherGuy = getGuy();
this sets the reference to the same reference as the guy member of foo.
I you want to "copy" object you might want to have a look for Object.clone()
Upvotes: 1
Reputation: 533540
Java variables can only contain primitives and references. Person
is a reference to an object. (You don't have to use &
like you might in C++ because its the only option)
When you do
Person anotherGuy = new Person(); // create a new object and assign the reference.
anotherGuy = getGuy(); // change the reference in `anotherGuy` to be the one returned by getGuy();
Upvotes: 0
Reputation: 298938
So
Person anotherGuy = getGuy();
and the above 2 lines, do the exact same thing?
No, the other version creates a new Person() object first and then discards it (which is just a waste of memory and processor cycles).
Upvotes: 1