Why is the toString() method being called when I print an object?

前端 未结 5 548
北海茫月
北海茫月 2020-11-27 06:36

I can\'t seem to understand why when I use println method on the quarter object, it returns the value of the toString method. I never called the toString method why am I g

5条回答
  •  温柔的废话
    2020-11-27 06:50

    Because all classes in java are subclasses of java.lang.Object , so whenever you try to call System.out.println() method to print object, it calls the toString() method of Object class.

    For Security Reasons the method prints a hashcode, not the values of that object, but you have inherited that method in your class and extended its definition to print object values

    public String toString() {
            return "A Quarter is "+getValue();
        }
    

    So you get a return value.

提交回复
热议问题