(参考自疯狂系列,李刚视频教程)
【toString】
——顾名思义:将任何对象都转化为字符串的表达形式!
在很多使用场合,都会重写该方法,用于将对象内部内容用想要的字符串形式输出;
不重写的话,只会输出对象的字符串表示:包名.类名@hashCode方法的返回值(16进制)。
写一个类,再输出该类的对象:
class Apple1 //类默认继承Object
{
private String color;
private double weight;//实例成员变量
//构造器
public Apple1()//无参构造器
{
}
public Apple1(String color , double weight)//初始化全部成员变量的构造器
{
this.color = color;
this.weight = weight;
}
//color的set和get方法
public void setColor(String color)//方法
{
this.color = color;
}
public String getColor()
{
return this.color;
}
//weight的set和get方法
public void setWeight(double weight)
{
this.weight = weight;
}
public double getWeight()
{
return this.weight;
}
}
public class Apple2Test
{
public static void main(String[] args)
{
Apple1 ap = new Apple1("红色",20);
System.out.println(ap);
System.out.println(ap.toString());
}
}
输出对象ap的返回值为:
toString()方法:
——程序打印对象(或者把对象转字符串)时,实际上输出的是该对象的 toString方法的返回值。
**即: 下式的输出相同:**
System.out.println(ap);
System.out.println(ap.toString());
Object提供的toString方法,返回的是:包名.类名@hashCode方法的返回值(十六进制) 没有设置包,则不打印包名。
有的地方说是返回对象的地址,其实是不严密的,是错的,验证:
—— 在Apple1类中加入hashCode方法
public int hashCode()
{
return 20;
}
输出为:
其中14为20的十六进制表示方法,说明:
——如果不写hashCode方法,toString返回值确实是对象的地址,写了就返回hashCode方法的返回值。
即:输出对象 = 输出toString方法的返回值 = 类名@hashCode方法的返回值
【小应用】通过toString来之间输出对象的内部状态
在类中对toString方法进行重写,使之返回对象的内部状态:
@Override
public String toString()//方法的重写,使输出对象时输出该方法的返回值!
{
return "Apple[color ="+color+",weight="+weight+"]";
//打印出所有的成员变量,以便看出对象的内部状态
//利用好toString,可以通过直接输出对象ap来查看对象的内部状态
}
输出对象:
System.out.println(ap);
可得对象的状态:
若要把对象转化为字符串输出,可以将对象加上一个空字符串:
String str = ap + "";//任何对象,加上空字符串,就会变成字符串
System.out.println(str);
即可输出上面的结果。