From the course: Java Design Patterns: Creational

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Dealing with mutability

Dealing with mutability - Java Tutorial

From the course: Java Design Patterns: Creational

Start my 1-month free trial

Dealing with mutability

- [Instructor] Problems can arise with the Cloneable interface when classes have fields that are mutable. If the field types are primitive values like string or int, there will probably not be any issues, but if the field types are other classes, there may be problems. In this example, there is a class called Rabbit and another class called Person. The Person class has a field called Name, and methods to get and set the name of the person. The Rabbit class has fields for age and breed and also a field called owner, which is of type Person. The SetOwner method in the Rabbit class takes a parameter of type string and creates a new Person object whose name is the string. The Rabbit class also has a clone method that creates a copy of the rabbit it is called on. In the main class, a rabbit object is created. The owner of the rabbit is set to a person called Sally and then a second object called rabbitCopy is created, which is a clone of the first rabbit. It then prints out the names of…

Contents