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 ?
Yes, your example is perfectly fine.
Furthermore, I think it’s pretty good design. One further refinement suggested by @duffymo is to use
Liston the left-hand side:This way
datais declared in terms of the abstract list interface, and not in terms of a concrete list implementation.