Force subclass to override method with itself as parameter

  • A+

I have an abstract Event class which has an abstract method:

abstract boolean intersect(Event object); 

This method should check if two instances of an Event subclass intersect based on the instance variables of the particular subclass. I want to force any subclass of Event to override the method on its instance variables. What is the best way to design this? This is my current implementation, which is wrong since I am changing the parameter type. I have also tried using interfaces, but have run into similar problems with type parameters.

@Override public boolean intersect(SubClassEvent e2) {      boolean intersects = false;     if(this.weekDay == e2.weekDay) {         if (this.getStartTime() < e2.getStartTime() && this.getEndTime() > e2.getStartTime()) {             intersects = true;         }         else if(this.getStartTime() >= e2.getStartTime() && this.getStartTime() < e2.getEndTime()){             intersects = true;         }     }     return intersects; } 


If you make the abstract class generic, you can achieve that:

abstract class Event<T extends Event<T>> {     abstract boolean intersect(T object); } 

Subclasses will have to declare their own type as parameter. Unless your codebase uses raw types, this should work.

class SubClassEvent extends Event<SubClassEvent> {      @Override     boolean intersect(SubClassEvent object){return true;} } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: