super.clone() in deep copy in java | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

super.clone() in deep copy in java

//this is an incomplete code public Object clone() // override clone method { Employee emp; try { emp = (Employee) super.clone(); emp.address = (Address) address.clone(); } catch(CloneNotSupportedException e) { return null; // will never happen } return emp; } // Question: why the super.clone() can be downcasted as it is the parent object

21st Mar 2021, 9:41 AM
Zhengrong Yan
Zhengrong Yan - avatar
1 ответ
0
Downcasting is allowed when there is a possibility that it succeeds at run time. As long as the super object could reference a subclass object, it works. You did not share any information about the super class, but you should always check it with the instanceof operator to avoid any runtime errors.
21st Mar 2021, 11:55 PM
Adrian
Adrian - avatar