Hullo all,
Wondering if there are any Java hackers who can clue me in at to why the following doesn't work:
public class Parent {
public Parent copy() {
Parent aCopy = new Parent();
...
return aCopy;
}
}
public class ChildN extends Parent {
...
}
public class Driver {
public static void main(String[] args) {
ChildN orig = new ChildN();
...
ChildN copy = orig.getClass().cast(orig.copy());
}
}
The code is quite happy to compile, but decides to throw a ClassCastException at runtime D=
Edit: Whoah, really quick replies. Thanks guys! So it seems I cannot downcast using this method... is there any other way to do downcasting in Java? I did think about having each ChildN
class overwrite copy()
, but wasn't enthusiastic about adding the extra boilerplate code.