You cannot cast a "Child" object to its "Parent" like this... Though it will compile ,on runtime java identifies that p1 holds a reference which is not assignment compatiable with c1 and will throw java.lang.ClassCastException: Parent
The p1, referencing to a Parent Object, cannot be cast to Child because a Parent is not a Child. But a Child is a Parent since the Child inherits all the methods in Parent class. However, if p1 is referencing to a Child object or a subclass of Child, then you can cast p1 to Child.
because sql.Date is a sub-class of util.Date. then why not this,
Child c = (Child)new Parent(); // Child is a sub-class of Parent
Joined: Jul 11, 2003
I received "java.lang.ClassCastException" for the above line.
Joyce [ September 28, 2004: Message edited by: Joyce Lee ]
Joined: Sep 26, 2003
Originally posted by adeel ansari: the problem is not that. as we can pass java.sql.Date to java.util.Date, without any casting. java.util.Date d = new java.sql.Date(); and we can do vice versa by add casting like, java.sql.Date d = (java.sql.Date)new java.util.Date(); because sql.Date is a sub-class of util.Date. then why not this, Child c = (Child)new Parent(); // Child is a sub-class of Parent
Without the cast to Child you would get a compile time error. The cast tells the compiler that you really mean to do this and the actual type of Parent does not get resolved until runtime. Casting down the object hierarchy is a problem, as the compiler cannot be sure what has been implemented in descendent classes. Casting up is not a problem because sub classes will have the features of the base classes. This can feel counter intuitive if you are aware that with primitives casting is allowed for widening operations (ie byte to int).