The code I wrote for training:
class Korobka {
public double width, depth, height; // Declare variables
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 ("Box length" + width);
System.out.println ("Box width" + depth);
System.out.println ("Box height" + height);
System.out.println ("Box volume" + 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 thought of the clone ()
method from the Object
class to apply.
Questions:
- Can I apply this method, for example, to the
k1
box (for cloning)? - If yes, how to do it?
Answer 1, authority 100%
In addition to the previous answers, I want to point out 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 ();
}
}
//all the rest
}
Since you specified the Cloneable
interface, CloneNotSupportedException
should never happen, and users of your class shouldn’t bother with it by wrapping calls in try-catch. In addition, you can be sure that the returned object is of type Korobka
and typecast 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 times 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 then a little differently:
Korobka copy = new Korobka (k1);
Answer 2, authority 15%
Yes you can. In java, objects are passed by reference. Those. following code
Object o1 = new Object ();
Object o2 = o1;
creates a single object pointed to by two references. Very often this is not convenient – we change the object o1, the object o2 is changed. And, for example, it was necessary to simply copy the values from o1 to the o2 object, but not 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 ();
}
//all the rest
}
Answer 3, authority 8%
First, you need your Korobka
class to implement the Cloneable
marker interface.
Next, you need to override the clone ()
method and make it public. Then you can clone boxes anywhere in your code.
P.S. Before overriding a method, read about deep copying objects in Java . Although it won’t come in handy here, read it anyway.