How to create an Immutable class that has a mutable object as refernce

I am asking a very simple question on how to create an immutable object in java.

So, I have one third-party Address class that does not inherit any Cloneable interface and its mutable class. Looks like this

public class Address {

    private String city;
    private String address;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Now I have another immutable class called Person, which implements the Cloneable interface, and also overrides the clone.Class method:

public class Person implements Cloneable {

    private String name;
    private Address address;

    public Person() {

    }

    public Person(String name, Address address) {
        this.name = name;
        this.address = address;
        //this.address = (Address) address.clone();
    }

    public String getName() {
        return name;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person person = (Person) super.clone();
        return super.clone();
    }

    public Address getAddress() {
        return address;
    }

    @Override
    public String toString() {
        return "name:" + name + ", address" + address.getAddress() + ", city="
                + address.getCity();
    }

}

Now my question is: I can clone an object of the Person class, but how to clone an instance of the class is cloned. I also read an article on shallow cloning and deep cloning. But I could not understand how deep cloning can be accomplished using the thirty-processor API. Or correct me if I understand something wrong about cloning.

+4
2

, : clone - , ( Java). , final.

, , .

serialize-deserialize , , .

+4

Cloneable , super.clone() , -fix- . final . , , , .

, Cloneable , .

, copy factory , . clone(), , - , Strings.

0

Source: https://habr.com/ru/post/1599118/


All Articles