I have following base class
class Base<T> {
// ...
}
and I have this class to extend the Base
class Derived extends Base<String> {
public void doSomething(String param) { // this works
}
public void doSomething(Base::T param) { // this DOES NOT work
}
}
I want know whether there is a java trick to get the second function definition to work without using the concrete class String directly?
Yes I have a reason. There are many classes need extend the Base with different concrete type. I want to avoid change the funciton signature in each class, this should be avoided if possible.
If you have many classes that need to extend the Base<T> class and they all have a doSomething method, you should probably put the doSomething in Base<T>:
class Base<T> {
public void doSomething(T param) {} // or even make this abstract
}
And then, IDEs like IntelliJ IDEA can generate the overridden method for you. When you start typing the method name, this pops up:

You press enter, and then it will be generated for you.
@Override
public void doSomething(String param) {
super.doSomething(param);
}
I suspect that you might be copy and pasting the implementation of doSomething, because otherwise why you think it is annoying to change the parameter type for each implementation?
If the implementations are mostly the same, consider having the doSomething method in the Base<T>, then extract the parts that are different into a doSomethingImpl method which will be overridden by the derived classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With