Search code examples
javaarraylistsuperclass

Inherit ArrayList from superclass


I have an ArrayList in a class called QuantityCatalogue and i made another class that extends the first class.(public class Buy extends QuantityCatalogue).How can i inherit the ArrayList that i made in QuantityCatalogue and use it in Buy class? Is this right?

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

Thank you in advance


Solution

  • Declare a private ArrayList field in superclass, declare a public setter method in supeclass, and in your subclass call this setter method to set the field'value:

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