博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

java 抽象父类方法返回子类的类型

Posted on 2018-02-09 14:53  钟悍  阅读(2027)  评论(0编辑  收藏  举报

背景:

在子类中想链式调用设值(或者builder模式),而有些属性在父类,有些在子类, 传统的方式需要在子类进行强制转换,而强制转换有影响链式调用。

例如:

父类:

public abstract class P {
    private String a;
    private String b;
    public String getA() {
        return a;
    }
    public P setA(String a) {
        this.a = a;
        return this;
    }
    public String getB() {
        return b;
    }
    public P setB(String b) {
        this.b = b;
        return this;
    }
}

子类:

public class S extends P {
    private String c;
    private String d;
    public String getC() {
        return c;
    }
    public S setC(String c) {
        this.c = c;
        return this;
    }
    public String getD() {
        return d;
    }
    public S setD(String d) {
        this.d = d;
        return this;
    }
}

测试:

   S s = new S();
   s.setC("c").setD("d").setA("a").setB("b");

   //compile error
   s.setA("a").setB("b").setC("c");

 

碰到这种情况, 泛型就可以起作用了, 可以让父类方法返回子类的类型

 

父类:

public abstract class Parent<E extends Parent<E>> {

    private String a;

    public E setA(String a) {
        this.a = a;
        return this.self();
    }

    public String getA() {
        return a;
    }

    public E self(){
        return (E)this;
    }
}

子类:

public class Son extends Parent<Son> {

    private String b;

    public Son setB(String b) {
        this.b = b;
        return this;
    }

    public String getB() {
        return b;
    }

    public static void main(String[] args) {
        Son son = new Son();
        son.setA("a").setB("b");
        System.out.println(son.getA()+" "+son.getB());
    }
}