0

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 ?

3 Answers 3

3

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

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

Comments

2

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.

1 Comment

I'd prefer List<ObjectInterface> on the LHS, but that's me.
2

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

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.