What is shallow copy in java

Difference between Deep and Shallow Copy in Java Object Cloning

Shallow copy and deep copy is related with cloning process so before go into the deep of shallow and deep copy we need to understand what is clone in java. Clone is nothing but the process of copying one object to produce the exact object, which is not guaranteed. We all know in Java object is referred by reference we can not copy one object directly to another object. So we have a cloning process to achieve this objective. Now one question arises in mind why we need this process so the answer is whenever we need a local copy of the object to modify the object in some method but not in the method caller.

So we can define Cloning as “create a copy of object “ .I think now we are somehow clear about cloning but there is more to it depending on how we are doing this copy, we can divide cloning into two types.

Before going into the deep of shallow and deep copy we need to understand how we achieve cloning in java.

How to Clone Objects in Java?

Difference between deep cloning vs shallow cloning in Java

In Java, everything is achieved through class, object, and interface.By default, no Java class support cloning but Java provide one interface called Cloneable , which is a marker interface and by implementing this interface we can make the duplicate copy of our object by calling clone() method of java.lang.Object class.

This Method is protected inside the object class and Cloneable interface is a marker interface and this method also throw CloneNotSupportedException if we have not implemented this interface and try to call clone() method of Object class.

By default any clone() method gives the shallow copy of the object i.e. if we invoke super. clone() then it’s a shallow copy but if we want to deep copy we have to override the clone() method and make it public and give own definition of making copy of object. Now we let’s see what is shallow and deep copy of object in Java programming language.

1. Shallow Copy in Java

Whenever we use default implementation of clone method we get shallow copy of object means it create new instance and copy all the field of object to that new instance and return it as object type we need to explicitly cast it back to our original object.

This is shallow copy of the object. clone() method of the object class support shallow copy of the object. If the object contains primitive as well as non primitive or reference type variable In shallow copy, the cloned object also refers to the same object to which the original object refers as only the object references gets copied and not the referred objects themselves.

That’s why the name shallow copy or shallow cloning in Java. If only primitive type fields or Immutable objects are there then there is no difference between shallow and deep copy in Java.

Читайте также:  User agent selenium python chrome

2. Deep Copy in Java

Whenever we need own meaning of copy not to use default implementation we call it as deep copy, whenever we need deep copy of the object we need to implement according to our need. So for deep copy we need to ensure all the member class also implement the Cloneable interface and override the clone() method of the object class.

After that we override the clone() method in all those classes even in the classes where we have only primitive type members otherwise we would not be able to call the protected clone() method of Object class on the instances of those classes inside some other class. It’s typical restriction of the protected access.

Difference between Shallow and Deep Copy in Java

I think now we know what is deep and shallow copy of object in Java, let see some difference between them so that we can get some more clarity on them.

  • When we call Object.clone(), this method performs a shallow copy of object, by copying data field by field, and if we override this method and by convention first call super.clone(), and then modify some fields to «deep» copy, then we get deep copy of object. This modification is done to ensure that original and cloned object are independent to each other.

This is all about deep copy and shallow copy of objects in Java. Now the question comes when we use shallow copy and when go for deep copy, so the answer would be simple that if the object has only primitive fields or Immutable objects, then obviously we will go for shallow copy, but if the object has references to other mutable objects, then based on the requirement, shallow copy or deep copy can be chosen.

This means if the references are not modified anytime, then there is no point in going for deep copy, We can go for shallow copy. But if the references are modified often, then you need to go for deep copy. Again there is no hard and fast rule, it all depends on the requirement.

15 comments:

Cloning is flawed in Java, don’t use Cloning. If you want to create multiple clone of your object, consider using Copy Constructor. It’s easy to implement clone() method wrong than right. Reply Delete

If the object contains primitive as well as non primitive or reference type variable In shallow copy, the cloned object also refers to the same object to which the original object refers as only the object references gets copied and not the referred objects themselves.

This one was very confusing.
So the basic difference between shallow and deep copy is.
Shallow copy copies the primitive values as it is but for reference type it copies reference to the object and doesnt create the new object.

Читайте также:  Java swing закрыть окно через кнопку

Meanwhile in deep copy you can override the clone() method to copy the exact values in the new object you create which is deep copy Reply Delete

Excellent explanation. Thanks for your valuable time.

Thanks for such and detailed explanation.
Here i am copying sample example,

public static void main(String[] args) throws Exception AccountDetails accountDetails = new AccountDetails(«1111111111», «222»);
Account acc = new Account(«Old Name», «3333333333», accountDetails);
System.out.println(«Original Acc Object : » + acc);

Account clone = (Account) acc.clone();
System.out.println(«Cloned Acc Object : » + clone);

acc.setName(«New Name»);
acc.setAccountNumber(«000000000»);
acc.getAccountDetails().setAtmCardNumber(«888888888»);
acc.getAccountDetails().setCvv(«999»);

System.out.println(«Modified Acc Object :» + acc);

/*
* modifying original Account object does not affects the cloned object
* in deep copy
*/
System.out.println(«Cloned object after Acc modification : » + clone);
>
>

class Account implements Cloneable private String name;
private String accountNumber;
private AccountDetails accountDetails;

public Account(String name, String accountNumber,
AccountDetails accountDetails) super();
this.name = name;
this.accountNumber = accountNumber;
this.accountDetails = accountDetails;
>

public String getName() return name;
>

public void setName(String name) this.name = name;
>

public String getAccountNumber() return accountNumber;
>

public void setAccountNumber(String accountNumber) this.accountNumber = accountNumber;
>

public AccountDetails getAccountDetails() return accountDetails;
>

public void setAccountDetails(AccountDetails accountDetails) this.accountDetails = accountDetails;
>

@Override
protected Object clone() throws CloneNotSupportedException Account clone = (Account) super.clone();
clone.setAccountDetails((AccountDetails) clone.getAccountDetails()
.clone());
return clone;
>

@Override
public String toString() return name + » » + accountNumber + » » + accountDetails;
>
>

class AccountDetails implements Cloneable private String atmCardNumber;
private String cvv;

public AccountDetails(String atmCardNumber, String cvv) super();
this.atmCardNumber = atmCardNumber;
this.cvv = cvv;
>

public String getAtmCardNumber() return atmCardNumber;
>

public void setAtmCardNumber(String atmCardNumber) this.atmCardNumber = atmCardNumber;
>

public String getCvv() return cvv;
>

public void setCvv(String cvv) this.cvv = cvv;
>

@Override
public String toString() return atmCardNumber + » » + cvv;
>

@Override
protected Object clone() throws CloneNotSupportedException // TODO Auto-generated method stub
return super.clone();
>
>

Источник

What is shallow copy in java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

What is shallow copy? Explain with an example in Java.

Creating an exact copy of an existing object in the memory is known as cloning.

The clone() method of the class java.lang.Object accepts an object as a parameter, creates and returns a copy of it (clones).

In order to use this method, you need to make sure that your class implements the Cloneable interface.

Example

import java.util.Scanner; public class CloneExample implements Cloneable < private String name; private int age; public CloneExample(String name, int age)< this.name = name; this.age = age; >public void displayData() < System.out.println("Name : "+this.name); System.out.println("Age : "+this.age); >public static void main(String[] args) throws CloneNotSupportedException < Scanner sc =new Scanner(System.in); System.out.println("Enter your name "); String name = sc.next(); System.out.println("Enter your age "); int age = sc.nextInt(); CloneExample std = new CloneExample(name, age); System.out.println("Contents of the original object"); std.displayData(); System.out.println("Contents of the copied object"); CloneExample copiedStd = (CloneExample) std.clone(); copiedStd.displayData(); >>

Output

Enter your name Krishna Enter your age 20 Contents of the original object Name : Krishna Age : 20 Contents of the copied object Name : Krishna Age : 20

Shallow copy

Whenever you try to create a copy of an object using the shallow copy, all fields of the original objects are copied exactly. But, if it contains any objects as fields then, only references to those objects are copied not the compete objects.

Читайте также:  Zipping file in java examples

This implies that, if you perform shallow copy on an object that contains any objects as fields, since only references are copied in a shallow copy, both the original and copied object points to the same reference internally and, if you do any changes to the data using the copied object, they are reflected in the original object too.

Note − By default, the clone() method does a shallow copy.

Example

In the following example the StudentData class contains a String variable (name), an integer variable (age) and an object (Contact).

In the main method we are creating an object of the StudentData class and copying it. From the copied object we are changing the data(field values) of the reference used (Contact object). Then, we are printing the data of copied object first followed by data of the original one.

Since we have done a shallow copy (using clone() method), you can observe that the change done is reflected in the original object.

import java.util.Scanner; class Contact < private long phoneNo; private String email; private String address; public void setPhoneNo(long phoneNo) < this.phoneNo = phoneNo; >public void setEmail(String email) < this.email = email; >public void setAddress(String address) < this.address = address; >Contact(long phoneNo, String email, String address ) < this.phoneNo = phoneNo; this.email = email; this.address = address; >public void displayContact() < System.out.println("Phone no: "+this.phoneNo); System.out.println("Email: "+this.email); System.out.println("Address: "+this.address); >> public class StudentData implements Cloneable < private String name; private int age; private Contact contact; public StudentData(String name, int age, Contact contact)< this.name = name; this.age = age; this.contact = contact; >public void displayData() < System.out.println("Name : "+this.name); System.out.println("Age : "+this.age); contact.displayContact(); >public static void main(String[] args) throws CloneNotSupportedException < Scanner sc =new Scanner(System.in); System.out.println("Enter your name "); String name = sc.next(); System.out.println("Enter your age "); int age = sc.nextInt(); System.out.println("#############Contact details#############"); System.out.println("Enter your phone number: "); long phoneNo = sc.nextLong(); System.out.println("Enter your Email ID: "); String email = sc.next(); System.out.println("Enter your address: "); String address = sc.next(); System.out.println(" "); //Creating an object of the class StudentData std = new StudentData(name, age, new Contact(phoneNo, email, address)); //Creating a clone of the above object StudentData copiedStd = (StudentData) std.clone(); //Modifying the data of the contact object copiedStd.contact.setPhoneNo(000000000); copiedStd.contact.setEmail("XXXXXXXXXX"); copiedStd.contact.setAddress("XXXXXXXXXX"); System.out.println("Contents of the copied object::"); copiedStd.displayData(); System.out.println(" "); System.out.println("Contents of the original object::"); std.displayData(); >>

Output

Enter your name Krishna Enter your age 20 #############Contact details############# Enter your phone number: 9848022338 Enter your Email ID: krishna_example@gmail.com Enter your address: Hyderabad Contents of the copied object:: Name : Krishna Age : 20 Phone no: 0 Email: XXXXXXXXXX Address: XXXXXXXXXX Contents of the original object:: Name : Krishna Age : 20 Phone no: 0 Email: XXXXXXXXXX Address: XXXXXXXXXX

Источник

Оцените статью