r/learnjava • u/Jacksontryan21 • Nov 22 '25
Casting
I was going over assignments from a past java class and in one of our assignments, we implemented the Clonable interface and got this method:
public Ellipse clone(){
try{
return (Ellipse)super.clone();
}catch(CloneNotSupportedException Ex){
Ex.printStackTrace();
}
}
I was wondering how the line return (Ellipse)super.clone(); works. I understand that super.clone() returns an object, but how does that object get turned into an Ellipse?
3
Upvotes
View all comments
Show parent comment
1
u/BassRecorder Nov 22 '25
Cloning on the Object level is basically what is a 'memcpy' in C, i.e. you get an exact copy of the source object including any descriptive data. That's why the cast works.
Also, this will always compile as a cast from Object to anything is always valid. It *will* throw a ClassCastException, though, if the object isn't compatible with the target type.