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


    背景:

    在子类中想链式调用设值(或者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());
        }
    }
  • 相关阅读:
    逻辑回归问题(Logistic Regression)
    丑数
    用两个栈实现队列
    重建二叉树
    单变量的线性回归(Linear Regression with One Variable)
    机器学习
    二维数组中的查找
    面经
    亚信实习---->PLSQL链接Oracle
    亚信实习小练习
  • 原文地址:https://www.cnblogs.com/zhonghan/p/8435459.html
Copyright © 2020-2023  润新知