Java 为什么从构造函数自动调用toString()?

Java 为什么从构造函数自动调用toString()?,java,constructor,abstract-class,tostring,Java,Constructor,Abstract Class,Tostring,我有一个名为Expression的抽象类,它表示一个数学表达式的结果,还有一个名为AtomicExpression的类,它表示一个扩展了Expression的数学表达式的操作数AtomicExpression类具有方法toString()。令人费解的是,每当我初始化AtomicExpression的实例时,就会自动调用toString(),即使我没有显式调用它。我不明白这是怎么回事 最初我注意到toString()中的String.format在调用toString()之前返回了一个错误,所以我

我有一个名为
Expression
的抽象类,它表示一个数学表达式的结果,还有一个名为
AtomicExpression
的类,它表示一个扩展了
Expression
的数学表达式的操作数
AtomicExpression
类具有方法
toString()
。令人费解的是,每当我初始化
AtomicExpression
的实例时,就会自动调用
toString()
,即使我没有显式调用它。我不明白这是怎么回事

最初我注意到
toString()
中的
String.format
在调用
toString()
之前返回了一个错误,所以我决定在
toString()
中添加
System.out.println
,以便在每次调用
toString()
时从控制台查看

代码如下:

public abstract class Expression {
    private double expression;

    public Expression(double expression) {
        this.expression = expression;
    }
    public abstract double calculate();

    public boolean equals(Object o) {
        Expression e = (Expression) o;
        return this.expression == e.expression;
    }
}

public class AtomicExpression extends Expression {
    private double operand;
    private static final String BLANK = "";

    public AtomicExpression(double operand) {
        super(operand);
        this.operand = operand;
    }

    public double calculate() {
        return this.operand;
    }

    public String toString() {
        String s;

        if(this.operand == (int) this.operand) { //the operand is an integer
            //s = String.format("%d", this.operand);
            System.out.println("this.operand == (int) this.operand");
            s = BLANK + this.operand;
            return s;
        } else { //the num is a double
            s = BLANK + this.operand;
            return s;
        }

    }
}


public class Main {
    public static void main(String[] args) {
        AtomicExpression a = new AtomicExpression(5);
        //System.out.println(a);
    }
}

是什么让你认为toString被调用了?@Eran我从控制台看到消息“this.operand==(int)this.operand”被打印出来,而这个消息来自我的
toString()
你提供的代码并没有显示这一点,至少通过编译和运行是这样的。你确定这不是因为你在调试器中运行吗?您是如何执行此代码的?很可能,如果您正在查看局部变量等,请尝试在不调试的情况下运行。调试器通常调用toString来显示变量的内容