1、重写toString()方法的作用:

其实对于一般的对象来说都会有这个方法,这个方法的目的,主要就是将对象按字符串的方式输出出来,用白话说就是:使用文字描述这个对象里各个变量是什么值 ,这个变量是什么类型的变量等 ,并且任何类都从Object继承了这个方法。

2、不重写toString()方法的输出是什么:

你不重写toString()方法的话输出的就是一个内存地址,也就是哈希码值。并不是输出这个类的各个变量的值,记得不重写好像只打印对象的类型而已。返回的是 getClass().getName() + "@" +Integer.toHexString(hashCode());也就是 类名 + @ +hashCode的值。

3、举例

下面有个test1类,里面有两个变量,a,b,先不重写toString()方法,输出试试:

package com.test;

public class test1 {
    private int a;
    private String b;
    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
    public String getB() {
        return b;
    }
    public void setB(String b) {
        this.b = b;
    }
}

还有一个test11类用于测试:

package com.test;

public class test11 {
    public static void main(String[] args) {
        test1 t1 = new test1();
        t1.setA(11);
        t1.setB("hello");
        System.out.println(t1.toString());
    }
}

此时输出为:

 

  • com.test.test1@1540e19d

也就是说不重写toString()方法,得到的就是类名+@+hasCode的值。

此时将test1里面的toString()方法重写,在test1代码段里面加上下面重写方法:

@Override
    public String toString() {
        return "test1{" +
                "a=" + a +
                ", b='" + b + '\'' +
                '}';
    }

再次在tesi11里面打印输出,结果如下:

 

  • test1{a=11, b='hello'}

因此,重写toString()方法就是将对象按字符串的方式输出出来。