Search code examples
javacopycopy-constructorfinalserial-number

How to change a final variable with a Deep-Copy-Constructor?


I have to create a deep copy constructor of a Movie which should have the same serial like the committed Object. The first steps I think are already correct but when I try: "this.serial = that.serial" it gives a warning and says I can't override final variables.

I could solve this problem when I remove the final keyword, but that is not allowed. Can anyone help me to change the final int serial variable without removing the final keyword?

private int serial;
private String title;
private FSK fsk;
private boolean isRent;

private final int serial;
private static int nextSerial;

Movie(String title, FSK fsk) {
    this.title = title; 
    this.fsk = fsk;
    this.serial = nextSerial;
    nextSerial++;

}
Movie(Movie that) {
    this(new String(that.title), that.fsk);
    this.serial = that.serial;
    }

Solution

  • Don't call the other constructor: this(new String(that.title), that.fsk);

    You are getting this error because this.serial is getting set in the other constructor you call. Once a final variable is set, you cannot set it again. That is why you're getting the error.