You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么Java中Builder类的setter可链式调用,普通类实例的setter不行?

核心差异原因

两类类的setter方法返回值设计不同,AlertDialog.Builder的setter方法返回当前Builder实例本身,而NormalAlert的常规setter方法返回值为void,这是两段代码编译结果不同的根本原因。

链式调用的实现原理

Java中要实现方法链式调用,要求每个实例方法调用结束后都返回当前对象实例,这样上一个方法的返回值就能直接作为下一个方法的调用主体。

AlertDialog.Builder的setter实现

其内部setter的典型实现逻辑如下:

public class AlertDialog {
    public static class Builder {
        private String applyButtonText;
        private String contentText;

        public Builder setApplyButton(String text) {
            this.applyButtonText = text;
            return this; // 核心:返回当前Builder实例
        }

        public Builder setText(String text) {
            this.contentText = text;
            return this;
        }
    }
}

调用new AlertDialog.Builder().setApplyButton("apply")后,返回值就是原Builder实例,因此可以直接继续调用setText()方法,完全符合Java语法规则。

NormalAlert的常规setter实现

普通业务类的setter一般采用Java常规写法,返回值为void:

public class NormalAlert {
    private String applyButtonText;
    private String contentText;

    public void setApplyButton(String text) {
        this.applyButtonText = text;
        // 无返回值
    }

    public void setText(String text) {
        this.contentText = text;
    }
}

调用new NormalAlert().setApplyButton("apply")执行完成后没有返回任何对象,void类型不能作为调用主体执行后续的setText()方法调用,因此编译报错。

补充说明

这种setter返回自身的设计是Builder模式的典型实现,目的是减少冗余变量声明、简化对象构建流程,同时可以在最终build方法执行前统一做参数校验,保证构建出的对象合法性。


内容的提问来源于stack exchange,提问作者kelsanity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 06:36:02