How do I apply the clone() method of the Object class?
The code I wrote for training:
class Korobka {
public double width, depth, height; //Объявление переменных
public static int id = 4;
Korobka(double w, double d, double h) {
width = w;
depth = d;
height = h;
}
double volume() {
return width * depth * height;
}
void measurement() {
System.out.println("Длина коробки " + width);
System.out.println("Ширина коробки " + depth);
System.out.println("Высота коробки " + height);
System.out.println("Объем коробки " + volume());
}
public static void main(String[] args) {
Korobka k1 = new Korobka(4.5, 3.6, 3.7);
Korobka k2 = new Korobka(4, 5, 6);
k1.measurement();
k2.measurement();
int ID = Korobka.id;
System.out.println(ID);
}
}
I decided to use the clone()
method from the Object
class.
Questions:
- Can I apply this method, for example, to the
k1
box (for cloning)? - If so, how do I do it?
3 answers
In addition to the previous answers, I want to note that it is better to implement clone()
like this:
class Korobka implements Cloneable {
@Override
public Korobka clone() {
try {
return (Korobka)super.clone();
}
catch( CloneNotSupportedException ex ) {
throw new InternalError();
}
}
//всё остальное
}
Since you have specified the Cloneable
interface, CloneNotSupportedException
should never happen, and users of your class should not have to suffer with it by wrapping calls in try-catch. In addition, you can be sure that the returned object is of type Korobka
and cast the type yourself. Then users can simply write:
Korobka copy = k1.clone();
In general, cloning has a lot of problems and it is not always good (although there are some cases when it is very convenient). An alternative to cloning is the copy constructor:
class Korobka {
Korobka(double w, double d, double h) {
width = w;
depth = d;
height = h;
}
Korobka(Korobka other) {
this(other.width, other.depth, other.height);
}
}
Use it a little differently then:
Korobka copy = new Korobka(k1);
Yes, you can. In java, objects are passed by reference. I.e., the following code
Object o1 = new Object();
Object o2 = o1;
Creates a single object that is pointed to by two references. Very often this is not convenient - changing the object o1 changes the object o2. And, for example, it was necessary to simply copy the values from o1 to the object o2, but not to link them in any way.
For this purpose, the Cloneable interface was introduced. In your class, you need to implement it:
class Korobka implements Cloneable {
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
//всё остальное
}
First, you need your Korobka
class to implement the token interface Cloneable
.
Next, you need to redefine the clone()
method and make it public. Then you can clone the boxes anywhere in your code.
P.S. Before redefining the method, read about deep object copying in Java. Although it is not useful here, but still read it.