0

Essentially, I am making a small program that deals with double values and enums as inputs and returns some output. The problem is that I need to make a new object as such:

For this problem I am unable to import classes or use static methods, so I have been trying to clone the two objects without any imported classes. I'm unsure if my "Example z = new Example(t)" line is false or what. I can set the values of 't' to another set private 'Example' object, but I don't know how to send that information to the object 'z'.

public class Example{
    private double temp;
    private Scale scale;
    private char start;
    public Example(double temp){...}
    public Example(double temp, Scale scale){...}
    public Example(Example input){
              /*I don't know what to put in here in order
              in order to copy the input to a new object*/
    }
}

public class Test{
    public static void main(String[] args){
    Example t = new Example(-10000.1, Scale.FAHRENHEIT);
    Example z = new Example(t);
}

2 Answers2

2

You can use any of the following techniques based on your use case:

  • Use clone() if the class implements Cloneable.
  • Create a clone manually. If there is a constructor that accepts all parameters, it might be simple, e.g new Example( ex.temp, ex.scale, ... ).
  • Use serialization. If your object is a graph, it might be easier to serialize/deserialize it to get a clone.

you can refer to this for code samples

Ratish Bansal
  • 1,982
  • 1
  • 10
  • 19
2
public Example(Example input){
    this.temp = input.temp;
    this.scale = input.scale;
    this.start = input.start;
}

might help ;)

nologin
  • 1,402
  • 8
  • 15
  • You'd have to extract the primitives from the `Scale` object as well – Garikai Feb 03 '19 at 17:30
  • Don't think so. Guess a this = input might work too. The new objects address reference based on this. – nologin Feb 03 '19 at 17:48
  • By assigning `this = input` you're essentially changing the reference of your object (applies to any other reference type for that matter) to that of `input` and not cloning the object; such that any subsequent changes you make to`input` will reflect on the new object – Garikai Feb 03 '19 at 17:54
  • Ok, you are right! – nologin Feb 03 '19 at 17:59
  • As the OP didn't say he wants a deep copy, this looks good! – kai Feb 03 '19 at 19:48