I'm delving into the Java 8 innovations, and I'm trying to call a default method which I implement in a high-level interface, even when a subclass overrides it. I would have no problem going back to implementing a Comparator
in my BusinessLogic
class, but I was wondering if there's some magic that lets me use the nifty new ::
.
Code:
public interface IdEntity extends Comparable<IdEntity> {
int getId();
@Override
default int compareTo(IdEntity other) {
return getId() - other.getId();
}
}
public class Game implements IdEntity {
@Override
public int compareTo(IdEntity o) {
if (o instanceof Game) {
Game other = (Game) o;
int something;
// logic
return something;
}
return super.compareTo(o);
}
}
public class BusinessLogic {
private void sortList(List<? extends IdEntity> list) {
// for Game, Game::compareTo gets called but I want, in this call only, the default method
Collections.sort(list, IdEntity::compareTo);
}
}
One way would be to put the compare method in a static method:
Then your method would be: