当前位置:优学网  >  在线题库

关于java继承的问题请教

发表时间:2022-06-23 10:20:42 阅读:80
import java.util.HashMap;

class R extends HashMap<String, Object> {

    public R() {
        put("code", 0);
        put("msg", "success");
    }

    public static R ok() {
        return new R();
    }

    public static R ok(String msg) {
        R r = new R();
        r.put("msg", msg);
        return r;
    }

    // 这里不理解,为什么是super.put,而不是this.put
    public R put(String key, Object value) {
//        super.put(key, value);
        this.put(key, value);
        return this;
    }

}

public class R_test {
    public static void main(String[] args) {
        System.out.println(R.ok().put("a", "aaa"));
    }
}

有个地方不是很理解,就是put方法中,为什么要用super.put,不能用this.put。我的理解是,子类继承父类,可以调用父类的方法,但用this.put会报错,请问是为什么?

🎖️ 优质答案
  • this.put 是递归调用自己,super.put 是调用父类中定义的 put,是原功能实现。

    这个类重载 put 大概只是为了能 return this 链式调用吧

  • 相关问题