Hazim
Hazim

Reputation: 381

Access subclass variables in an ArrayList?

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?

Upvotes: 0

Views: 920

Answers (2)

John3136
John3136

Reputation: 29265

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

Upvotes: 1

Paul Boddington
Paul Boddington

Reputation: 37645

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.

Upvotes: 2

Related Questions