toString方法是一个很特殊的方法,他是属于object类中的一个实例方法,Java中所有的类都是object中的子类,故所有的Java对象都具有toString方法.他是一个自我描述的方法,当你打印对象时,toString方法就会返回this对象的实现类的:“类名+@+hashCode”,通过重写toString方法就能按要求打印对象。举例如下:
package 练习题;
public class apple {
private String color;
private double weight;
public apple(){}
apple(String a,double b)
{
color=a;
weight=b;
}
void set(String a,double b)
{
this.color=a;
this.weight=b;
}
public String toString()
{
return "苹果的颜色是"+color+" ,重量是"+weight;
}
public static void main(String args[])
{
apple a=new apple("red",5.677);
System.out.println(a);
}
}