I am learning Java for a test (tomorrow) and am wondering about a question that will probably never come up but has got me curious.
Is it possible to create a new collection class such as a list or something that can hold only a specific type and not its sub-types? Would I use generics to achieve this goal?
Not really, or at least not practically.
Subtypes should operate like sets in mathematical set theory. If B is a subset of A, any item in B is also an item in A.
In the same way, if B is a subtype of A, any item in B is also an item of A. Thus, any collection of A must be able to maintain items of B.
That being said, there may be convulted ways that B can override certain operations to explicitly break the ability to use it in a collection or to instantiate it.
I don’t think generics will solve that problem.