Prasanna Peethambaram’s Post

📄Java clone() 1️⃣ What clone means Shallow copy → copy the Object reference Deep copy → copy the Object reference+ copy their fields deeply 2️⃣ What Java actually does by default super.clone() ➡ Copies object structure ➡ Inner objects are shared So Java clone copies: ✔ primitives ❌ references (pointer copied, not object) 3️⃣ How we make it Deep Copy Manually clone inner objects: new Location(this.location) So: super.clone() + manual cloning = Deep Copy 4️⃣ Return Type Confusion Java forces method signature: Object clone() Compiler only sees Object So we cast: User copy = (User) original.clone(); 🧠 Casting does NOT create or convert objects It only changes how compiler views the reference 5️⃣ What actually happens internally clone() → memory duplication (no constructor called) Casting → only permission to access methods Object ref = userClone; ((User)ref).getName(); // allowed after cast No new object created here. 6️⃣ Important internal fact clone() in Object is a native method Real implementation exists inside JVM (C/C++), so IDE cannot open its source code. return (User) super.clone(); → works, but only shallow copy return new User(this); → works and can be deep copy GitHub Link: https://lnkd.in/g5Zj48m6 🔖Frontlines EduTech (FLM) #java #coreJava #BackendDevelopment #Programming #CleanCode #ResourceManagement #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs #cloneMethod #deepCopy #shallowCopy

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories