覆盖继承中的方法

时间:2011-09-13 21:35:29

标签: java inheritance

import java.util.AbstractList;

公共类ItemSet扩展了AbstractList {

private Item[] arr;
private ItemClass itemClass;

public ItemSet(Item item) {
arr = new Item[1];
arr[0] = item;
}

/*
 * (non-Javadoc)
 * 
 * @see java.util.AbstractList#add(java.lang.Object)
 */
@Override
public boolean add(Item e) {
boolean isNotAdded = true;
for (int i = 0; i < arr.length; i++) {
    if (e.getRule().compareTo(arr[i].getRule())) {
    if (e.getDot() == arr[i].getDot()) {
        isNotAdded = false;
        break;
    }
    }
}
if (isNotAdded) {
    Item[] oldArr = arr;
    arr = new Item[oldArr.length + 1];
    System.arraycopy(oldArr, 0, arr, 0, oldArr.length);
    arr[oldArr.length] = e;
}
return isNotAdded;
}

@Override
public Item get(int index) {
return arr[index];
}

@Override
public int size() {
return arr.length;
}

// SETTER

/**
 * @param itemClass
 *            the itemClass to set
 */
public void setItemClass(ItemClass itemClass) {
this.itemClass = itemClass;
}

//

// GETTER

/**
 * @return the itemClass
 */
public ItemClass getItemClass() {
return itemClass;
}
//

}

如何覆盖例如删除方法? 如何不使用自己的列表实现?

2 个答案:

答案 0 :(得分:3)

如果您不想在界面中实现其他方法,只需定义它们以引发异常:

public bool remove(Object o)
{
    throw new UnsupportedOperationException();
}

如果你不想这样做,你应该继承一个类,而不是实现一个接口。

答案 1 :(得分:-1)

如果您不想继承remove(),请不要扩展AbstractList,而是将您想要的方法委派给ArrayList

喜欢这样(并且为了上帝的爱,不要评论你的二传手和吸气鬼)

    public class ItemSet {
    private final ArrayList<Item> items = new ArrayList<Item>();
    private ItemClass itemClass;

    public ItemSet(Item item) {
        items.add(item);
    }

    public boolean add(Item e) {
        boolean isNotAdded = true;
        for (Item item : items)
            if (e.getRule().compareTo(item.getRule()))
                if (e.getDot() == item.getDot()) {
                    isNotAdded = false;
                    break;
                }
        // why are you adding here?
        if (isNotAdded)
            items.add(e);
        return isNotAdded;
    }

    public Item get(int index) {
        return items.get(index);
    }

    public int size() {
        return items.size();
    }

    public void setItemClass(ItemClass itemClass) {
        this.itemClass = itemClass;
    }

    public ItemClass getItemClass() {
        return itemClass;
    }
}
}