what is shallow copying ?

Dani AI

Generated

Shallow copying: a new top-level object is created but its fields are copied "as is." For primitive fields that means values are duplicated. For reference fields that means the references are copied, so both objects point at the same nested objects. That is different from Java assignment, which does not create any new object — it simply makes two variables refer to the same object.

Example sketch (illustrates the difference):

MyObject a = new MyObject();
MyObject b = a;             // assignment: no copy, a and b point to the same object

MyObject c = new MyObject(a); // shallow copy: new MyObject, but internal references are shared

MyObject d = a.deepCopy();    // deep copy: new MyObject and new copies of nested objects

Practical notes: use a copy constructor or a static factory to make copies you control. A shallow copy is OK when nested objects are immutable (for example, String) or when shared mutability is intended. For mutable nested state that must be independent, implement a deep copy that constructs new nested instances. The built-in clone() mechanism exists but is tricky to use correctly; many developers prefer copy constructors or factory methods instead. More background and guidelines are in the Java tutorial on cloning and the general discussion of deep vs. shallow copy (Java Cloning tutorial, ).

To address : when you do obj2 = obj1 you are not getting a member-wise copy — you are copying the reference. As linked to a resource earlier, the key distinction is whether you create a new container object (shallow copy) or also create new nested objects (deep copy). Choose the approach that matches whether nested objects must remain independent or may be shared.

http://www.devx.com/tips/Tip/13625

thankx

but in Java we can directly asign one object to another

then other case ie; member wise assigning is not comng

am i right ..............

am a bit confused

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.