开发者

Proper way to create superclass from subclass

开发者 https://www.devze.com 2023-04-09 11:04 出处:网络
I have an client-server application. The client has a class: Item.java public class Item public string name;

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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号