Java中如何在toString()方法中正确引用其他方法的变量?
核心问题定位
- 在构造方法
Donation(String organization, double amount, boolean tax)方法体中定义的v、org、b属于方法局部变量。这类变量的作用域仅覆盖当前方法的执行流程,方法执行完成后变量就会被从内存栈中清除,不属于类实例的组成部分,因此同属一个类的toString()方法根本无法引用到这些变量。 - 对访问修饰符的作用认知存在偏差:
public/private等修饰符仅可作用于类层面的成员(字段、方法、内部类),无法修饰方法内部定义的局部变量——哪怕在构造方法内写public double v = amount;这类代码,编译阶段就会直接报错。要实现类内不同方法的变量共享,必须把变量定义为类的成员字段,而不是声明在某个方法的方法体内部。 - 原有
toString()方法存在语法和逻辑错误:v是double类型的数值变量,不能直接作为布尔表达式放在if()的判断条件中;原有分支的判断顺序完全颠倒,和捐赠类的业务逻辑不匹配。
修正后的可运行代码
class Donation { // 将原局部变量提升为类的私有成员字段,实现类内方法的共享访问 private double v; private String org; private boolean b; public static void main(String[] args) { Donation uw1 = new Donation("University of Washington", 600.75, true); Donation uw2 = new Donation("University of Washington", 40, true); Donation sj = new Donation("Snap Judgment", 30, false); Donation tal = new Donation("This American Life", 40, true); Donation mc = new Donation("Microphone Check", 99.99, false); System.out.println(uw1.toString()); System.out.println(uw2.toString()); System.out.println(sj.toString()); System.out.println(tal.toString()); System.out.println(mc.toString()); } public Donation(String organization, double amount, boolean tax) { // 通过this关键字给类的成员字段赋值,不再重新创建和成员字段同名的局部变量 this.v = amount; this.org = organization; this.b = tax; } @Override public String toString(){ // 修正判断逻辑:可抵税(b为true)的捐赠额前加*标记,不可抵税的返回普通格式文本 if (b) { return "* $" + v + ": " + org; } return "$" + v + ": " + org; } }
注:原代码中导入的
java.util.Scanner未被实际使用,属于冗余导入,不影响代码运行,可按需删除。
代码运行预期输出
* $600.75: University of Washington * $40.0: University of Washington $30.0: Snap Judgment * $40.0: This American Life $99.99: Microphone Check
内容的提问来源于stack exchange,提问作者Karl.52
相关产品推荐
相关产品推荐

