Marc Rasmussen
Marc Rasmussen

Reputation: 20555

Using Interface as parameter in list

My question is rather simple. Im trying to make a builder for building charts. The chart data will be filled by an object depending on what program my fellow programmers create Therefore ive used an interface called ObjectInterface to make sure that there are certain methods the an object always have.

My question is if i want to add these objects (that i do not know of which type) to an ArrayList is it possible to add them such as this:

ArrayList<ObjectInterface> data = new ArrayList<ObjectInterface>();
ObjectType Test = new ObjectType("Test");
data.add(test);

in this example the ObjectType is an object that implements the ObjectInterface

is this legal ?

Upvotes: 0

Views: 75

Answers (3)

SkyWalker
SkyWalker

Reputation: 14309

If ObjectType is a subtype (or implementation) of ObjectInterface then it is legal. Don't you have a Java compiler? it will answer all your "is this legal" type of questions ;)

Upvotes: 3

NPE
NPE

Reputation: 500367

Yes, your example is perfectly fine.

Furthermore, I think it's pretty good design. One further refinement suggested by @duffymo is to use List on the left-hand side:

List<ObjectInterface> data = new ArrayList<ObjectInterface>();

This way data is declared in terms of the abstract list interface, and not in terms of a concrete list implementation.

Upvotes: 2

reprogrammer
reprogrammer

Reputation: 14718

Yes, it is legal. You can add subtypes of ObjectInterface, e.g., ObjectType, to ArrayList<ObjectInterface>.

Upvotes: 2

Related Questions