背景:

在子类中想链式调用设值(或者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());
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-29
  • 2021-07-14
  • 2021-08-19
  • 2022-12-23
  • 2021-10-09
猜你喜欢
  • 2022-03-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-10
  • 2022-12-23
相关资源
相似解决方案