Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload abstract methods in abstract class

I want to have an abstract class that has an abstract method, say abstract void compare(). But the parameters it takes should vary according to different implementations in different subclasses. I wonder what is the right way to do this?

I cannot overload it by writing different signatures of it in the abstract class itself, because if I do so, any of its subclasses would need to implement all the versions, which is not what I want. Thanks.

like image 878
J Freebird Avatar asked Feb 02 '26 15:02

J Freebird


2 Answers

Assuming that each version of compare() will all have the same number of parameters (which they should), you could use generics so that subclasses can define what the types of the parameters are.

abstract <I, J> void compare(I arg1, J arg2);
like image 81
gla3dr Avatar answered Feb 04 '26 04:02

gla3dr


You should use Generics to do it :

public abstract class AbstractClass<T>{
public abstract void compare(T element);
}

And in the implementation you write this :

Public class MyImpl extends AbstractClass<SpecificType>{
public void compare(SpecificType elemental{
// do stuff
}
}
like image 25
Bouhanef Avatar answered Feb 04 '26 04:02

Bouhanef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!