如何实现Java方法连续链式调用(如qns.answer(5).answer(7))
问题原因
- 你当前的
answer方法返回值为String类型,String类不存在answer方法,因此第一次调用answer后得到的字符串实例无法再调用answer,自然抛出cannot find symbol错误。 - 原类设计中没有存储临时回答值的字段,无法满足「链式调用不修改原实例状态」的要求(你的示例中调用完
answer后原qns实例输出仍为0)。 - 原有代码的构造方法中
this.correctAns = correctAns末尾缺少分号,属于语法错误需要先修复。
实现方案
要实现无副作用的链式调用,调整逻辑如下:
- 新增
final修饰的currentAns字段存储当前回答值,默认值为0,匹配原有toString的输出逻辑 - 新增重载私有构造方法,用于每次调用
answer时生成新的Question实例,不修改原实例状态 - 修改
answer方法返回值为Question类型,每次调用返回持有新回答值的实例 - 调整
toString方法直接读取currentAns输出,无需硬编码0
修改后的完整代码
class Question { private final String question; private final int correctAns; // 新增字段存储当前回答值,默认值为0 private final int currentAns; // 对外公开的构造方法,默认currentAns为0 public Question(String question, int correctAns) { this.question = question; this.correctAns = correctAns; this.currentAns = 0; } // 内部使用的构造方法,生成带指定currentAns的新实例 private Question(String question, int correctAns, int currentAns) { this.question = question; this.correctAns = correctAns; this.currentAns = currentAns; } // 修改返回值为Question,返回新实例实现链式调用 public Question answer(int myAns) { return new Question(this.question, this.correctAns, myAns); } @Override public String toString() { return String.format("%s: My answer is %d.", this.question, this.currentAns); } }
效果验证
调用逻辑完全符合你给出的示例要求:
// 实例化时传入问题和正确答案两个参数 Question qns = new Question("How many apples are there in the bag?", 10); System.out.println(qns); // 输出:How many apples are there in the bag?: My answer is 0. System.out.println(qns.answer(12)); // 输出:How many apples are there in the bag?: My answer is 12. System.out.println(qns.answer(12).answer(4)); // 输出:How many apples are there in the bag?: My answer is 4. System.out.println(qns); // 输出:How many apples are there in the bag?: My answer is 0.
内容的提问来源于stack exchange,提问作者Samantha P
相关产品推荐
相关产品推荐

