だから私は3つのクラスがあります:
Item
GroupItem
伸びるItem
ProductItem
拡張アイテム
オブジェクトの配列をItem
クラスに渡し、クラス タイプに応じて個別に処理したいと考えています。
これを行うのに許容できる方法を使用するか、指定されたサブクラスの初期化時に設定されるinstanceof
内部メソッドを使用する必要があります。boolean isGroup()
class Item {
protected boolean isGroup = false;
public boolean isGroupItem() { return isGroup; }
}
class GroupItem extends Item {
public GroupItem() {
isGroup = true;
}
}
class ProductItem extends Item {
public ProductItem() {
isGroup = false;
}
}
class Promotion {
// Item can be either a group or a list of items
private List<Item> items = new LinkedList<Item>;
public void addItem(Item itemObj) {
items.addItem(itemObj);
}
public List<Item> getItems() {
return items;
}
}
class Checker {
// Items retrieved from Promotion and passed from another class as array
public Checker(Item[] items) {
// either
if(items[0] instanceof GroupItem) {
// Do something ...
}
// or
if(items[0].isGroupItem()) {
// Do something ...
}
}
}
だから私の質問は:
- インスタンスまたはメソッド?
- メソッドの場合、アイテムまたはプロモーションで?
- なぜ?(理由がよくわかるように)
前もって感謝します