Java 为什么打印整型对象会打印其int值?

Java 为什么打印整型对象会打印其int值?,java,Java,我可以创建自定义类对象并使它们以相同的方式运行吗?e、 g- 如果我有课: class MyCustomClass{ int myDisplayValue; public MyCustomClass(int value){ this.myDisplayValue = value; } } 我用它来表示: class TestClass{ public static void main(String[] args){ MyCusto

我可以创建自定义类对象并使它们以相同的方式运行吗?e、 g-

如果我有课:

class MyCustomClass{
    int myDisplayValue;
    public MyCustomClass(int value){
        this.myDisplayValue = value;
    }
}
我用它来表示:

class TestClass{
    public static void main(String[] args){
        MyCustomClass testObj1 = new MyCustomClass(8);
        System.out.println(testObj1); // prints the class name with some random text
        Integer testObj2 = new Integer(8);
        System.out.println(testObj2); // prints the int value '8'
    }

有没有办法让testObj1也打印“8”?我意识到这可能没有任何用处,还有其他更安全地打印值的方法,我只想知道这是否可行。

重写toString方法并返回整数的字符串

 @Override
 public String toString(){
      return String.valueOf(myDisplayValue);            
 }

重写每个对象都具有的toString方法。