This content has been marked as final.
Show 1 reply
-
1. Re: Up-/Downcasting from objects with partial db-update
fhh Jan 29, 2007 3:35 PM (in response to hamtho2)You cannot do that. I do not mean you cannot do that with JPA but you cannot do that in Java (or any other sane programming language).
You can upcast refernces to objects but not the objects themsleves, eg.public class Human { } public class Man extends Human { private String name; public Man(String name) { this.name = name; } } Human being = new Man("Adam"); Man adam = (Man)being;
This will work because "being" always references an object of the class Man. But you want to do something like:Human being = new Human(); Man adam = (Man)being;
This will not work because the referenced object "being" is just a human - not yet a man. Changing the object class after creation would put the object in an undefined state - in this example you would have a man without name.
So you cannot do what you want to do without copying the values. The easiest way is to create a constructor which takes the subclass object as an argument:public class Man extends Human { private String name; public Man(Human human, String name) { super(); this.inheritedValue = human.inheritedValue; this.name = name; } public Man(String name) { this.name = name; } }
However, I would not recommend resusing the id - eben if it might be possible. You are dealing with a new object here so I would rather delete the old one and then insert the new one.
Regards
Felix