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

背景:测试

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

例如:this

父类:spa

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;
    }
}

子类:code

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;
    }
}

测试:blog

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

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

 

碰到这种状况, 泛型就能够起做用了, 可让父类方法返回子类的类型get

 

父类:class

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());
    }
}
相关文章
相关标签/搜索