Question

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

Was it helpful?

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

OTHER TIPS

Declare it protected in the super class, then the variable is also visible to child classes. public is also possible but possibly opens the variable scope too much for your use case. And if your child class is in the same package, you can also use the default modifier.

A completely different option is to provide a getter/setter functions like this:

private ArrayList<String> items;

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

protected void setItems(ArrayList<String> items) {
    this.items = items;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top