3

I have many classes that implement an interface. Can I have Stacks, Queues and ArrayLists defined like this?

ArrayList<Class<? extends BaseClass>> 

to store objects ? In my scenario each object will be from a different class in the Stack, or ArrayList? What are the pros and cons of such an implementation? I am new to Java and hence this question. Any alternate recommendation to this?

3
  • You can. The pros and cons depend on what you need it for. Commented Jul 1, 2016 at 3:20
  • 5
    The list you've defined is of classes, not objects of those classes. If you want a list of objects that extend BaseClass, you are looking for ArrayList<BaseClass>. Commented Jul 1, 2016 at 3:27
  • Oh Thanks. I was confused there as well. I wrote the anology that way because when we declare ArrayLists, we give the class names inside. So ArrayList<BaseClass> will simply allow me to hold objects of all classes that implement the interface BaseClass? Commented Jul 1, 2016 at 17:19

2 Answers 2

6

Yes, you can.

The pros are that you can store various types of objects and be assured they implement the same contract and therefore can treat them polymorphically. You wouldn't be able to store them otherwise in the single structure without using Object; assuming no other commonality exists.

The cons are that you won't know, without additional checks, their type and therefore are limited to the functionality provided by that interface. You'd then me stuck doing the check for the instance type followed by a cast in order to use the uncommon functionality.

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

Comments

2

I have many classes that implement an interface

If BaseClass is that interface and you wish to store any sub type of BaseClass in ArrayList or Stack, declaration ArrayList<Class<? extends BaseClass>> is wrong for that purpose. It would simply be like,

List<BaseClass> arrList = new ArrayList<BaseClass>();

Can I have Stacks , Queues and ArrayLists defined like this?

Yes, you can define ArrayList or Stack on base type interface and put in Objects of concrete sub classes.

In my scenario each object will be from a different class in the Stack, or ArrayList?

Yes, if you have inserted so. You are allowed to insert any sub type of BaseClass in that ArrayList so if you have put such elements , those will be there.

What are the pros and cons of such an implementation?

These would be same as already listed in ChiefTwoPencils's answer - that you have liberty to store various types of Objects in one List but when you retrieve objects from list to work on, you might have to check their type etc ( if interested in some that sub type's specific behavior ).

Hope it helps !!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.