通过重写toString改变控制台打印行为

在Java中,所有的对象都隐式继承Object类,Object类有toString方法,所以所有Java类实际上都有toString方法。当编译器需要一个String而你却只有一个对象时,该方法就会被调用。 默认的,我打印一个对象,实际上是打印了这个对象的类的类名+“@”符号+能代表该类的无符号的十六进制的HashCode:

public class Mobile {
    private String manufacturer;
    
    public Mobile(String manufacturer) {
        this.manufacturer = manufacturer;
    }
    
    public static void main(String[] args){
        Mobile mobile = new Mobile("HuaWei");
        System.out.println(mobile);
    }
}

// output:com.dhcc.mhealth.web.jklapi.unit.test.Mobile@1175e2db

但是我重写toString方法,就可以改变打印到控制台的行为:

public class Mobile {
    private String manufacturer;
    
    public Mobile(String manufacturer) {
        this.manufacturer = manufacturer;
    }
    
    @Override
    public String toString() {
        return manufacturer;
    }
    
    public static void main(String[] args){
        Mobile mobile = new Mobile("HuaWei");
        System.out.println(mobile);
    }
}

// output: HuaWei

猜你喜欢

转载自blog.csdn.net/weixin_34850743/article/details/87445558