How does System.out.print() work?

后端 未结 9 2234
鱼传尺愫
鱼传尺愫 2020-11-27 03:40

I have worked with Java for a quite a long time, and I was wondering how the function System.out.print() works.

Here is my doubt:

Being a functi

9条回答
  •  猫巷女王i
    2020-11-27 04:26

    You can convert anything to a String as long as you choose what to print. The requirement was quite simple since Objet.toString() can return a default dumb string: package.classname + @ + object number.

    If your print method should return an XML or JSON serialization, the basic result of toString() wouldn't be acceptable. Even though the method succeed.

    Here is a simple example to show that Java can be dumb

    public class MockTest{
    
    String field1;
    
    String field2;
    
    public MockTest(String field1,String field2){
    this.field1=field1;
    this.field2=field2;
    }
    
    }
    
    System.out.println(new MockTest("a","b");
    

    will print something package.Mocktest@3254487 ! Even though you only have two String members and this could be implemented to print

    Mocktest@3254487{"field1":"a","field2":"b"}
    

    (or pretty much how it appears in the debbuger)

提交回复
热议问题