Search code examples
javaparameter-passingabstract-class

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.


Solution

  • 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) {
    
        }
    }