Skip to content
Advertisement

Not able to create generic bounded class objects with interface

I am trying to use bounded types with generics to create generic objects of subclasses (these implement an interface). But I am getting type mismatch errors when initializing objects with the subclasses.

Here is the interface:

JavaScript

Here’s the class that implements this interface:

JavaScript

Now I created 2 classes (SegmentPageScanResult and ItemProcessor) with the bounded generic type as:

JavaScript

and

JavaScript

When I am trying to initialize the SegmentPageScanResult and try calling submitAndExecute method of ItemProcessor from a Unit test as follows:

JavaScript

I get the error –

JavaScript

Can someone please help me understand why I am not able to initialize the generic object with the class implementing the interface?

Advertisement

Answer

I think you might have done:

JavaScript

And you also have:

JavaScript

So when you call:

JavaScript

There is a mismatch between the type of the itemProcessor (Attachment) and SegmentPageScanResult (ScannableEntity). So you probably need to create the ItemProcessor and the SegmentPageScanResult with the same type parameter.

EDIT: It’s not completely clear what you are trying to achieve but maybe this can help:

JavaScript

So the SegmentPageScanResult no longer has a type parameter because it only handles ScannableEntity instances. To allow setting different types from each ItemProcessor, the method parameter allows subtypes with List<? extends ScannableEntity>

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement