The Object clone() Method

Similar documents
Cloning Enums. Cloning and Enums BIU OOP

Shallow Copy vs. Deep Copy

Basic Keywords Practice Session

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed.

Import Statements, Instance Members, and the Default Constructor

The Java Main Method

Chapter 14 Abstract Classes and Interfaces

Java Object Oriented Design. CSC207 Fall 2014

Objects and Iterators

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

Checked and Unchecked Exceptions in Java

Inheritance and Polymorphism in Java

public Candy() { ingredients = new ArrayList<String>(); ingredients.add("sugar");

Loops. In Example 1, we have a Person class, that counts the number of Person objects constructed.

Programming II (CS300)

List ADT. Announcements. The List interface. Implementing the List ADT

And Even More and More C++ Fundamentals of Computer Science

Programming II (CS300)

Chapter 13 Abstract Classes and Interfaces

INHERITANCE AND EXTENDING CLASSES

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Abstract Classes and Interfaces

Rules and syntax for inheritance. The boring stuff

Immutables. At first glance, you d think that immutables were useless, however, they provide many advantages.

Tecniche di Progettazione: Design Patterns

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

Inheritance and Interfaces

The static keyword Used to denote fields and methods that belong to a class (but not to any particular object).

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

A simple map: Hashtable

Tecniche di Progettazione: Design Patterns

C++ Important Questions with Answers

Static Imports, Default Values, Number Types and More!

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Class, Variable, Constructor, Object, Method Questions

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

Tirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Chapter 13 Abstract Classes and Interfaces. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class

Exercises Software Development I. 08 Objects II. Generating and Releasing Objects (Constructors/Destructors, this, Object cloning) December 3rd, 2014

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

ArrayList. Introduction. java.util.arraylist

Written by John Bell for CS 342, Spring 2018

Inheritance and Polymorphism

Chapter 4 Defining Classes I

C++ Inheritance and Encapsulation

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Ryerson University Department of Electrical & Computer Engineering COE618 Midterm Examination February 26, 2013

C# Programming for Developers Course Labs Contents

java.lang.object: Equality

to avoid building a class hierarchy of factories that parallels the class hierarchy of products; or

Inheritance. Inheritance

CS 61B Discussion 5: Inheritance II Fall 2014

Java Collections Framework

INHERITANCE. Spring 2019

Object Oriented Programming. What is this Object? Using the Object s Slots

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

Introduction to Programming Using Java (98-388)

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

INHERITANCE AND TYPE HIERARCHIES. Prof. Chris Jermaine

INTERFACE WHY INTERFACE

C++ Inheritance and Encapsulation

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Outline. 15. Inheritance. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff

Chapter 13 Abstract Classes and Interfaces

Lesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014

CS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

TaxiBot New attributes Variables Math! TaxiBot

More on Objects in JAVA TM

Array Based Lists. Collections

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

UMBC CMSC 331 Final Exam

16 Multiple Inheritance and Extending ADTs

COMP 250 Fall inheritance Nov. 17, 2017

CSE wi Final Exam 3/12/18 Sample Solution

15CS45 : OBJECT ORIENTED CONCEPTS

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Thinking Functionally

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Test-Driven Development (TDD)

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

CMSC 132: Object-Oriented Programming II

copy.dept_change( CSE ); // Original Objects also changed

QUIZ. What is wrong with this code that uses default arguments?

CS 251 Intermediate Programming Exceptions

Logistics. Final Exam on Friday at 3pm in CHEM 102

Annotation Hammer Venkat Subramaniam (Also published at

CORE JAVA TRAINING COURSE CONTENT

Implications of Substitution עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

step is to see how C++ implements type polymorphism, and this Exploration starts you on that journey.

COE318 Lecture Notes Week 8 (Oct 24, 2011)

Relationship of class to object

Programming Language Concepts: Lecture 7

17 Multiple Inheritance and ADT Extensions

Polymorphism and Interfaces. CGS 3416 Spring 2018

Transcription:

The Object clone() Method Introduction In this article from my free Java 8 course, I will be discussing the Java Object clone() method. The clone() method is defined in class Object which is the superclass of all classes. The method can be used on any object, but generally, it is not advisable to use this method. The clone() Method The clone() method, as the name implies, creates an identical copy of an object. Depending on the type of implementation, this copy can either be a shallow or a deep copy. In any case, the objects will be equal, but not identical (For more details see my article about Identity and Equality in Java). Using clone() on an Object Let s take a look at how the clone() method works. In Example 1 we create an object of class Porsche named marcusporsche, giving me a very nice new car. However, I m a nice guy and I d like to give away another Porsche; so I ll clone the marcusporsche object and assign the new object to the reference variable peterporsche. If your name is Peter, congratulations! You just got a new Porsche! package com.marcusbiel.java8course; public class PorscheTest { Example 1 @Test public void shouldcloneporsche(){ Porsche marcusporsche = new Porsche(); Porsche peterporsche = porsche.clone(); assertnotsame(porsche, peterporsche);

However, something is still wrong. The clone() method is red. The problem is that the clone() method from class is Object protected. Every object can call protected methods inherited from the Object class on itself. However, it can never call such a method on other objects. While clone() is accessible to both our Porsche class and our PorscheTest class, the PorscheTest can never call the inherited clone() method of a Porsche object. To fix this problem, we have to override the clone() method in the Porsche class and increase its visibility. First, we change the access modifier of the clone() method to public and change the method return type from Object to Porsche, which makes our code clearer since we don t have to cast cloned objects into Porsches. To implement the clone method, we call super.clone(). The super keyword means that we are calling a method from a superclass, which in this case is the Object class. Note also that the clone method of the Object class is declaring a checked CloneNotSupportedException, so we have to decide whether we want to declare it or handle it. Declaring a CloneNotSupportedException while implementing (supporting) the clone() method is contradictory. Therefore, you should omit it. All possible error situations are serious errors, so the best you can possibly do is to throw an Error instead. package com.marcusbiel.java8course; public class Porsche implements Car { @Override public Porsche clone(){ try{ return(porsche)super.clone(); catch(clonenotsupportedexception e){ throw new AssertionError(); /* can never happen */ Example 2 However, when we run the above code, we encounter another issue: a CloneNotSupportedException. To correct that, we have to implement the Cloneable interface. The Cloneable interface does not contain any methods, it is a Marker Interface - an empty interface used to mark some property of the class that implements it.

public class Porsche implements Car, Cloneable{ Example 3 Now when we run the test in Example 1, it passes successfully. Modifying an Object after clone() At this point, we re going to add a test to check the content of the new object. We want to verify that our owner has been correctly identified in each object. The asstring() method will be used to return a String representation of our Porsche object. The expected result when we are finished is for the object to be Porsche of Peter. First, I m going to create the asstring() method in our Porsche class and an owner attribute. String ownername; [...] public String asstring(){ return Porsche of + ownername; Example 4 In the code below, the assertequals() function is used to compare the output of the asstring() function. When we run the test, it will fail, as the owner of both Porsches is still Marcus. @Test public void shouldcloneporsche(){ Porsche marcusporsche = new Porsche( Marcus ); Porsche peterporsche = porsche.clone(); assertnotsame(porsche, peterporsche); Example 5 assertequals( Porsche of Peter, peterporsche.asstring());

To fix this test, we need to create a method for transferring ownership of the car. I m going to call this method sellto(). public void sellto(string newownername){ ownername = newownername; Example 6 Now I will call the sellto() method on the cloned Porsche object, to transfer ownership of the cloned Porsche to Peter. As a final proof that cloning the Porsche object created a fully independent second Porsche object, I will test that transferring the ownership to Peter on our cloned Porsche object did not influence the original Porsche object. In other words, I will test whether the original Porsche object still belongs to Marcus or not. @Test public void shouldcloneporsche(){ Porsche marcusporsche = new Porsche( Marcus ); Porsche peterporsche = porsche.clone(); assertnotsame(porsche, peterporsche); Example 7 peterporsche.sellto( Peter ); assertequals( Porsche of Marcus, porsche.asstring()); assertequals( Porsche of Peter, peterporsche.asstring()); This time, when we run the test, it will pass. This proves that we have created two independent objects that can be changed independently, so our cloning method works as expected. Using clone() on an Array As I've said before, it is generally not advisable that the clone method be used. However, one case where I do recommend its use is for cloning arrays, as shown in example 8. Here, we create an array of type String. We call the array.clone() method, using our array, and assign the new cloned array to a reference variable called copiedarray. To prove that this not just a reference to the same object, but a new, independent object, we call the assertnotsame() with our original array and our newly created copiedarray. Both arrays have the same content, as you can see when we print out the copiedarray in a for-each loop.

@Test public void shouldclonestringarray() { String[] array = { one, two, three ; String[] copiedarray = array.clone(); assertnotsame(array, copiedarray); for(string str: copiedarray){ System.out.println(str); Example 8 The clone() method copies every string object in the array into a new array object that contains completely new string objects. If you ran the code above, the clone() method would work as expected and the test would be green. In this case, the clone() method is the prefered technique for copying an array. Clone() works great with arrays of primitive values and immutables, but it doesn t work as well for arrays of objects. As a side note, in the Java Specialists Newsletter Issue 124, by Heinz Kabutz, a test was performed that showed that the clone() method is a bit slower for copying very small arrays, but for large arrays, where performance matters most, it s actually faster than any other method of copying arrays. Alternatives to Clone(): The Copy Constructor There are two recommended alternatives to using the clone() method that deal with the shortcomings of clone(). The first method is using a copy constructor that accepts one parameter - the object to clone. A copy constructor is really nothing very special. As you can see in Example 8, it is just a simple constructor that expects an argument of the class it belongs to. The constructor then copies (clones) all sub-objects. If the new object just references the old sub-objects, we call it a shallow copy. If the new object references truly copied objects, we call it a deep copy. You can learn about this topic by reading my article Shallow vs Deep Copy.

package com.marcusbiel.java8course; public class BMW implements Car, Cloneable { Example 9 private Name ownersname; private Color color; public BMW(BMW bmw) { this.ownersname = new Name(bmw.ownersName); this.color = new Color(bmw.color); Alternatives to Clone(): The static Factory Method The other alternative is a static factory method. As the name implies, a static factory method is a static method, used to create an instance of the class. It can also be used to create a clone. There are a few common names for static factory methods; I m going to use newinstance(). I ve also created the same method for Name and Color, in order to recursively perform the operation on all sub-objects. package com.marcusbiel.java8course; public class BMW implements Car, Cloneable { private Name ownersname; private Color color; public static BMW newinstance(bmw bmw){ return new BMW(Name.newInstance(bmw.ownersName), Color.newInstance(bmw.color)); public BMW(Name ownersname, Color color){ this.ownersname = ownersname; this.color = color; Example 10

Both of these alternatives are always better than the clone() method and produce the same result: a clone of the original object. The static factory method might be a bit more powerful than the copy constructor in certain cases, but generally both lead to the same result. Immutables The last thing I d like to do in this article is take a look at the Name class: package com.marcusbiel.java8course.car; public class Name implements Cloneable{ private String firstname; private String lastname; public static Name newinstance(name name){ return new Name(name.firstName, name.lastname); Example 11 Notice however, that the String members are passed by reference, without creating a new object. The reason for that is that String is an Immutable object. An Immutable object will not be changed by the reference in the new object, and therefore can be safely used without cloning. This is an extremely important concept that applies when you are trying to create a Deep Copy. If you are interested, you can read more about creating Immutables in my article about Immutables which is coming soon! Thanks for reading! 2017, Marcus Biel, Software Craftsman https://cleancodeacademy.com All rights reserved. No part of this article may be reproduced or shared in any manner whatsoever without prior written permission from the author