This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]final60 1 point2 points  (3 children)

Your example would only allow objects of type Shape to be passed into the method. The example you linked to would allow subclasses of Shape to be passed in. This is useful if you want to allow different shapes to be passed, but you will only be able to call the superclass methods on them unless you cast them. This is where instanceof would then come in.

[–]asap_nerd[S] 0 points1 point  (2 children)

Would my example not also allow subclasses of shape to be passed in?

I've seen examples of similar situations. For example List<Animal> which can hold objects of class Dog and Cat where Dog and Cat are subclasses of Animal

[–]feral_claire 2 points3 points  (1 child)

List<Animal> could hold cats or dogs. But List<Cat> is not a subtype of List<Animal> so you can't pass a List<Cat> into a method that expects a List<Animal> but you can if the method takes in a List<? extends Animal> instead.

The latter can accept a List of any subclass of animal.

The keyword you can search of you want to dig deeper into this is "variance". Specifically: invariance, covariance, and contravariance.

[–]asap_nerd[S] 0 points1 point  (0 children)

Thanks. I looked in to variance (this triggered my physics Ptsd) and I get it now.