0

Can someone explain object cloning,what is given in the comments in the code- -https://code.sololearn.com/cKO7sy0uisr4/?ref=app

Object cloning-https://code.sololearn.com/cKO7sy0uisr4/?ref=app

27th Dec 2019, 4:31 PM
Ajoh Pv
Ajoh Pv - avatar
5 Réponses
0
Object ref1=ref.clone(); Emp ref2=(Emp)ref1; //Line 1- A reference variable of Object type is initialized with a copy of your object of "Emp" class. It is legal since the Object class is the Super class of every class you create in Java. //Line 2- Your Object type variable which hold the copy of your "Emp" object is type casted to "Emp" so that it can be stored by a "Emp" type reference.
27th Dec 2019, 5:02 PM
Avinesh
Avinesh - avatar
0
Why should I do downcasting(line 2) ,whats the use
27th Dec 2019, 5:09 PM
Ajoh Pv
Ajoh Pv - avatar
0
Can't I put ref1.empname just like that?
27th Dec 2019, 5:10 PM
Ajoh Pv
Ajoh Pv - avatar
0
Because your ref1 is of Object type so you cannot directly assign it to "Emp" without casting. You will probably get a type mismatch error or something.
27th Dec 2019, 5:13 PM
Avinesh
Avinesh - avatar
0
because Object.clone() returns Object not Emp but Object has not properties like Salary EDIT2: your attempt is interesting, but then you can't clone Emp object in other class outside Emp. Solution is implement clone() in Emp public class Emp implements Cloneable{ //.. public Emp clone() { Emp emp = null; try { emp = (Emp) super.clone(); } catch (CloneNotSupportedException e) { System.out.println("cloning not supported"); } return emp; } public static void main(String[] args) { //.. Emp ref2 = ref.clone(); } }
27th Dec 2019, 8:36 PM
zemiak