从超类继承ArrayList

时间:2014-05-04 13:08:59

标签: java arraylist superclass

我在一个名为QuantityCatalogue的类中有一个ArrayList,我创建了另一个扩展第一个类的类。(public class Buy extends QuantityCatalogue)。我如何继承我在QuantityCatalogue中创建的ArrayList并在Buy类中使用它? 这是对的吗?

public class Buy extends QuantityCatalogue
{
    public Buy(ArrayList<String> items,ArrayList<Integer> quantity)
    {
        super(items,quantity);
    }
}

提前谢谢

2 个答案:

答案 0 :(得分:0)

在超类中声明它protected,然后该变量对子类也是可见的。 public也是可能的,但可能会为您的用例打开变量范围。如果您的子类位于同一个包中,您也可以使用默认修饰符。

完全不同的选择是提供这样的getter / setter函数:

private ArrayList<String> items;

protected ArrayList<String> getItems() {
    return items;
}

protected void setItems(ArrayList<String> items) {
    this.items = items;
}

答案 1 :(得分:-1)

在超类中声明一个私有的ArrayList字段,在supeclass中声明一个公共setter方法,并在你的子类中调用这个setter方法来设置字段&#39;值:

 public class QuantityCatalogue {
        private ArrayList<String> items;

            //this method helps us change the value of field items
        public void setItems(ArrayList<String> items) {
            this.items = items;
        }

          .....
    }

    public class Buy extends QuantityCatalogue {
        public void someMethod(ArrayList<String> items) {
            //call setItems method of superclass
            this.setItems(items);
        }
    }
相关问题