Proper way to create superclass from subclass
I have an client-server application.
The client has a class: Item.java
public class Item
public string name;
public string size;
and the server has a class PersistableItem.java which lets me store it using JPA
public class PersistableItem extends Item
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long Id;
and sends it to the server which executes the addItemToServer method:
public void addItem( Item item){
//create PersistableItem from item
DAO.save([paramerter = PersistableItem]);
}
In my server method do I cast the 开发者_JS百科item as PersistableItem? Do i make a constructor in PersistableItem that takes in a Item?
What's the proper design here?
As you suggested, You can create a constructor in SomePersistedItem that takes a SomeItem. In the constructor, you call super with the name and size, so you have your SomePersistedItem correctly populated.
public class SomePersistableItem extends SomeItem
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
public SomePersistableItem(SomeItem originalItem) {
super(originalItem.getName(), originalItem.getSize());
}
And you just add it.
public void addItem( someItem item){
DAO.save(new PersistableItem(item));
}
That's assuming you have a constructor in SomeItem that takes a name and size. Else you use whatever method you have to build SomeItem (Factory, setters...)
I would make your persistable item extend an interface
public interface Persistable {
boolean persist();
}
public class SomePersistableItem extends SomeItem implements Persistable {
}
public void addItem(Persistable p) {
p.persist();
}
精彩评论