Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

java - 有没有一种方法可以对抽象方法进行模板化,以便抽象方法的参数与实现子类的类型相同?(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.

(我想避免使用接口或反射。)

  ask by Tyler Durden translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 , eg it would be possible to define class Sub_C extends Super<Sub_A> .

(据我所知,您不能强制子类将自身作为T传递,例如,可以定义class Sub_C extends Super<Sub_A> 。)

Not sure if that is a problem.

(不知道这是否是一个问题。)


Following java naming conventions it should look like:

(遵循Java命名约定,它应类似于:)

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

    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...