Why toString() is called automatically from constructor?

Viewed 395

I have an abstract class called Expression which represents the result of a math expression and the class AtomicExpression which represents an operand of a math expression which extends Expression. AtomicExpression class has the method toString(). Inexplicably, whenever I initialize an instance of AtomicExpression then toString() is called automatically even though I didn't call it explicitly. I don't understand how this can be.

Originally I noticed that String.format from toString() was returning an error before toString() would be called, so I decided to add System.out.println inside toString() to see from console each time a call would be made to toString().

This is the code:

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);
    }
}
0 Answers
Related