0

I have a Shop class that has an array list of type Worker, and I have two classes that inherit (extend) from Worker, called Stocker and Cashier.

My Stocker class adds the variable

int stamina;

and my Cashier class adds the variable

int patience;

Within Shop, I have an ArrayList named workers of type Worker, my questions are:

1) Is it wrong to be adding objects of types Stocker and Cashier into workers even though they both extend from the Worker class?

2) How can I access the variables of the subclasses from the ArrayList? I've tried to use:

workers.get(0).getStamina();

(knowing for a fact that I have added a class of type Stocker to my ArrayList at index 0) - however this does not work..

How can I freely access and use these subclasses from an ArrayList of type superclass?

2 Answers 2

2

You have to cast a Worker to a Stocker to do that:

((Stocker) workers.get(0)).getStamina();

However you may want to consider changing your design so that you do not have a list of items of different types.

Sign up to request clarification or add additional context in comments.

2 Comments

So make 3 different ArrayLists? One for Worker, Stocker, and Cashier? Is it wrong to make an ArrayList using subclasses of a superclass?
If you have an ArrayList, you should normally use the elements in the same way. Since you want to call different methods, 3 lists may be better
1

The ArrayList can store Workers and Stockers in the same collection, but if you say ArrayList<Worker> then the collection only knows about Workers and not Stockers.

You need something like:

Worker worker = workers.get(0);
if (worker instanceof Stocker)
{
    Stocker stocker = (Stocker)worker;
    //stocker.getStamina();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.