Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to template astract methods so that a parameter to an abstract method will be typed the same as the implementing subclass?

Is there a way to template astract methods so that a parameter to an abstract method will be typed the same as the implementing subclass? In other words if we have:

class Super {
    abstract void a_method( <Sub> param );
}

class Sub_A extends Super {
    void a_method( Sub_A param ){
        ...
    }

class Sub_B extends Super {
    void a_method( Sub_B param ){
        ...
    }
}

Then each subclass takes its own type as a parameter to this method. I would like to avoid using an interface or reflection.

like image 503
Tyler Durden Avatar asked Dec 01 '19 16:12

Tyler Durden


1 Answers

The normal way to do that is introduce a generic parameter:

abstract class Super<Sub extends Super> {
    abstract void a_method(Sub param);
}

class Sub_A extends Super<Sub_A> {
    void a_method(Sub_A param) {

    }
}

class Sub_B extends Super<Sub_B> {
    void a_method(Sub_B param) {

    }
}

As far as I know you cannot force the subclass to pass themselves as T, e.g. it would be possible to define class Sub_C extends Super<Sub_A>. Not sure if that is a problem.


Following java naming conventions it should look like:

abstract class Super<S extends Super> {
    abstract void aMethod(S param);
}

class SubA extends Super<SubA> {
    void aMethod(SubA param) {

    }
}

class SubB extends Super<SubB> {
    void aMethod(SubB param) {

    }
}
like image 76
luk2302 Avatar answered Oct 03 '22 16:10

luk2302