-1

I have some alternatives to Java cloning. Can I please have some help to describe how these alternatives work:

The alternatives are:

•   Using a copy constructor for creating a new object as a copy of an existing object

•   Creating your own interface with copy methods
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
user2230606
  • 89
  • 3
  • 9

2 Answers2

2

This is example of using a copy constructor for creating a new object as a copy of an existing object:

public class MyClass {
  private int myVar;
  public MyClass() { this.myVar = 0; }
  public MyClass(MyClass other) { this.myVar = other.myVar; }
}

And this is example of creating your own interface with copy methods

public interface MyCopy {
  Object copy();
}

public class MyClass implements MyCopy {
  private int myVar;
  public MyClass() { this.myVar = 0; }
  public MyClass(int myVar) { this.myVar = myVar; }
  public Object copy() { return new MyClass(myVar); }
}
gerrytan
  • 40,313
  • 9
  • 84
  • 99
0

"Using a copy constructor for creating a new object as a copy of an existing object"

public class SampleClass
{
    int x;
    int y;
    public SampleClass(SampleClass old)     // Copy Constructor
    {
        this.x = old.x;
        this.y = old.y;
    }

    public SampleClass(int x, int y)        // Regular constructor
    {
        this.x = x;
        this.y = y;
    }
}

The copy constructor creates a copy of an object which is passed into the constructor.

"Creating your own interface with copy methods"

Honestly not sure exactly what they're alluding to here. Perhaps they mean creating an interface with a copy() method in it which you can then implement, but I'm not sure why you wouldn't just use the Cloneable interface.

Daniel Centore
  • 3,220
  • 1
  • 18
  • 39