0

I would like to limit the compatible types of a method's input to a collection of a certain classes sub classes. However, I would only like to allow the first level down of the sub-classes to be accepted. For instance the class 'shape' has a variety of sub-classes eg. 'rectangle','circle','triangle'. Now 'rectangle' has it's own subclass 'square' so how would I limit the accepted collections to only accept the hierarchical level of sub-classes comprising of rectangle, circle and triangle without accepting square?

0                 shape
                /   |   \
1       rectangle circle triangle
            |
2       square

I know that to encompass all of the sub-classes of shape and their sub-classes I would do the following:

public void methodName(List<? extends shape>){ ... }

However, how would i restrict it to only one level of sub-classes down from shape? i.e ( only rectangle, circle, triangle )

Delrog
  • 735
  • 2
  • 11
  • 27
  • 3
    Short answer: you can't. Long answer: you caaaaaaaaaaaaan't, and also you shouldn't. – Louis Wasserman Feb 24 '16 at 20:44
  • 3
    If you find yourself in need of this, you need to take a step back and ask yourself if inheritance is indeed the correct way to model your problem. This isn't specific to generics either, it's inheritance in general. Just because in your original problem every `A` is a `B`, it doesn't necessarily mean that the class representing `A` should extend the class representing `B`. – biziclop Feb 24 '16 at 20:47

1 Answers1

0

If you're trying to do that, than you're violating the Liskov Substitution Principle.

In short it states that subclasses should be always accepted in place of their superclass. Conceptually, if a square is a rectangle, then how could it be, that it is not accepted when a rectangle is.

So, that all just means that you probably want to model your problem in a different way. You unfortunately did not mention what property the square has that makes it somehow not a rectangle.

That being said, making square a subclass of rectangle is usually problematic. See: https://en.wikipedia.org/wiki/Circle-ellipse_problem .

Robert Bräutigam
  • 7,514
  • 1
  • 20
  • 38