Java: How do I create a collection of a specific parent type and not subtypes of it?

I am learning Java for a test (tomorrow) and wondering about something that will probably never come, but I got curious.

Is it possible to create a new collection class like a list or something that can only contain a specific type and not its subtypes? Do I use generics to achieve this goal?

+1


source to share


4 answers


Not really, or at least practically.

Subtypes should work like sets in mathematical set theory. If B is a subset of A, any element from B is also an element in A.

In the same way, if B is a subtype of A, any element in B is also an element of A. Thus, any set of A must be able to support elements of B.



In this way, the ways in which B can override certain operations can be collapsed to explicitly violate the ability to use it in a collection or instantiate it.

I don't think generics will solve this problem.

+3


source


If you create your own collection class, you can check the class of the object on the insert using reflection and reject it if it is not of a particular exact type. Also, if you have control over the class definition for the class contained in the collection, ending it will prevent subclassing. (obviously this is a problem if you need subclasses for other uses)



+3


source


The question is why do you need it. If you have a list containing animals, why would you only want to fill that list with "basic animals", but forbid adding dogs or cats to the list. One of the basic concepts of OO is that you use a subclass instance wherever you need it, such as in the base class ( Wikipedia: Liskov's Substitution Principle ). If this does not apply in your situation, then something might be wrong with your class hierarchy.

+3


source


You can use "final" in the class definition of the containing class to prevent subtyping. I don't immediately see how you can test this, or restrict your generics to require final classes. You can use reflection to check if a class has the latest set of modifiers, for example when building a collection, and throw if it doesn't.

If the class itself is not final, you can check each added object to the collection to ensure that its execution class is exactly the class the collection wants and not a subclass.

see http://java.sun.com/docs/books/tutorial/reflect/ for information on reflection in Java.

+2


source







All Articles