Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force subclass to override method with itself as parameter

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;
}
like image 960
Nicolae Stroncea Avatar asked Nov 05 '18 05:11

Nicolae Stroncea


People also ask

How do you force a method to be overridden?

Just make the method abstract. This will force all subclasses to implement it, even if it is implemented in a super class of the abstract class. Show activity on this post.

Can subclass override methods?

Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.

Can a superclass override a subclass method?

If a method cannot be inherited, then it cannot be overridden. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. A subclass in a different package can only override the non-final methods declared public or protected.

When should you override a method in a subclass?

When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.


1 Answers

If you make the abstract class generic, you can allow subclasses to specify themselves as parameter type:

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

Subclasses will be able 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;}
}

The limitation of this (or rather exceptions to this) will be raw types and events of other types of events, which can allow other parameter types.

like image 180
ernest_k Avatar answered Sep 20 '22 05:09

ernest_k