How do u return a new object; an exact copy of the object which it is called?

J

Jazz

Hello All,

I was wondering, How do u return an exact copy of an object (Plate)
which it is called upon.

IE.

In the Main:

Plate p = new Plate();
Plate p2 = p.getCopy();

In the Class:
public Plate getCopy() {
???
}

What do i do for..???

i know ur prolly saying u can just go Plate p2 = p1, but I have my
reasons :p

Thanks

Jazz
 
J

Joona I Palaste

Jazz said:
Hello All,
I was wondering, How do u return an exact copy of an object (Plate)
which it is called upon.

In the Main:
Plate p = new Plate();
Plate p2 = p.getCopy();
In the Class:
public Plate getCopy() {
???
}
What do i do for..???
i know ur prolly saying u can just go Plate p2 = p1, but I have my
reasons :p

You will need to set every field of p2 to the same value as the field in
p. If there are object fields, then you need to decide whether you want
a shallow copy or a deep copy.
In a shallow copy, just copy the references. p and p2 will then include
references to the same objects. In a deep copy, make identical copies
of the objects, and copy references to those. p and p2 will then
include references to separate, but identical, objects.
 
M

Michael Borgwardt

Jazz said:
Hello All,

I was wondering, How do u return an exact copy of an object (Plate)
which it is called upon.

IE.

In the Main:

Plate p = new Plate();
Plate p2 = p.getCopy();

In the Class:
public Plate getCopy() {
???
}

What do i do for..???

Use the clone() method provided by Object. Implement Cloneable and

public Plate getCopy() {
return (Plate) super.clone();
}

Note that this will produce a "shallow copy".
i know ur prolly saying u can just go Plate p2 = p1,

No we're not, because that wouldn't be a copy.
 
K

Kristian Bisgaard Lassen

Hello All,

I was wondering, How do u return an exact copy of an object (Plate)
which it is called upon.

IE.

In the Main:

Plate p = new Plate();
Plate p2 = p.getCopy();

In the Class:
public Plate getCopy() {
???
}

What do i do for..???

i know ur prolly saying u can just go Plate p2 = p1, but I have my
reasons :p

Thanks

Jazz

Hi Jazz,

Java does not support cloning of object at compile time since it is
uncertain whether or not a field object is a part-of or reference-of
object (field primitives are easy since that is just a copy of the actual value).
This means you have to specify youself what you mean by cloning.
See http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Cloneable.html.

Best Regards
Kristian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top