Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Dynamic" Casting in Java

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.

like image 709
user50264 Avatar asked Dec 30 '08 20:12

user50264


1 Answers

Is like trying to do this:

  public Object copy(){
       return new Object();
  }

And then attempt to:

  String s = ( String ) copy();

Your Parent class and ChildN class have the same relationship as Object and String

To make it work you would need to do the following:

public class ChildN extends Parent {
    public Parent copy() {
        return new ChildN();
    }
}

That is, override the "copy" method and return the right instance.


EDIT

As per your edit. That is actually possible. This could be one possible way:

public class Parent {
    public Parent copy() {
        Parent copy = this.getClass().newInstance();
        //...
        return copy;
    }
}

That way you don't have to override the "copy" method in each subclass. This is the Prototype design pattern.

However using this implementation you should be aware two checked exceptions. Here's the complete program that compiles and runs without problems.

public class Parent {
    public Parent copy()  throws InstantiationException, IllegalAccessException  {
       Parent copy = this.getClass().newInstance();
       //...
       return copy;
    }
}
class ChildN  extends Parent {}

class Driver {
     public static void main(String[] args) throws  InstantiationException ,  IllegalAccessException  {
         ChildN orig = new ChildN();
         ChildN copy = orig.getClass().cast(orig.copy());
         System.out.println( "Greetings from : " + copy );
    }
}
like image 149
OscarRyz Avatar answered Oct 15 '22 10:10

OscarRyz