I am creating an abstract class, that will be implemented by some projects.
These projects, will implement that class, and their methods also.
protected String setExitStatus(SortDto sortDto) {
if (sortDto.getTotalNumberOfPages() > 0) {
return "DATOS";
} else {
return "SINDATOS";
}
}
As you can see, this method by defect has a SortDto as a parameter.
What if, the developer that wants to use that method, but don't want to (or does not have) to supply a SortDto, and instead wants to supply another dto? or another pair of dtos?
Is there any way I can define this method, that by default, wants a SortDto, but it can be override with another argument?
Generally speaking, there are two ways to implement what you assumedly have in mind.
One is the use of an interface
that SortDto
and all other classes that can be used as a parameter must implement. This interface would then be the type of the (badly named) setExitStatus
method. Within this interface, you need a method that generalizes the sortDto.getTotalNumberOfPages() > 0
condition.
interface DtoExit {
public boolean isDatos();
}
in SortDto
public class SortDto implements DtoExit {
...
@Override
public boolean isDatos() {
return sortDto.getTotalNumberOfPages() > 0;
}
}
Your initial method becomes
protected String setExitStatus(DtoExit dto) {
if (dto.isDatos()) {
return "DATOS";
} else {
return "SINDATOS";
}
}
The other possibility is to use polymorphism and create several setExitStatus()
methods with different parameter types.
protected String setExitStatus(SortDto sortDto) {
if (sortDto.getTotalNumberOfPages() > 0) {
return "DATOS";
} else {
return "SINDATOS";
}
}
protected String setExitStatus(AnotherDto anotherDto) {
if (anotherDto.someCondition()) {
return "DATOS";
} else {
return "SINDATOS";
}
}
...
(Theoretically, there is a third approach, as you could have just one method with a very general parameter type, like Object
, and do a lot of instanceof
checks in the method body to find out the actual type of the parameter and handle it accordingly. I will not provide an example fo this approach as it is a dirty hack and definitely not recommendable)