Skip to content
Advertisement

How to extends from generic type and override method parameter type with subclass

I have a problem with generic class hierarchy and method override. I tried to do something like below:

JavaScript

and the subclass looks like:

JavaScript

However, subclass does not compile and I have no clue how to declare method in Configuration class so I can override it in subclass with subclass type as parameter. I want to avoid explicit casting.

Advertisement

Answer

Due to Erasure: merge in Configuration becomes:

JavaScript

For ExtendedConfiguration to override merge, it must have Configuration as method param type. So, below ExtendedConfiguration is fine:

JavaScript

@Override instructs the compiler to check if the method is being inherited.

With the declaration in question:

JavaScript

it’s overloading instead. If you remove @Override, it will compile fine.


To achieve your requirement, you can use recursive generics:

The updated declarations may look like:

Configuration

JavaScript

ExtendedConfiguration

JavaScript

Read more here and here.

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