object类 & toString方法

object类

是所有java类的根基类

如果在类的声明中未使用extends关键字指明其基类,则默认基类为object类

ToString方法

object类中定义有 public String toString() 方法,其返回值是String类型,描述当前对象的有关信息。

在进行String与其它类型数据的连接操作时(如:System.out.println("info+person()),将自动调用该对象类的toString()方法

可以根据需要在用户自定义类型中重写toString()方法。

public class TestToString {
	public static void main(String[] args) {
	Dog d = new Dog();
	System.out.println("d:="+ d.toString());
	
	}
}

class Dog {
	public String toString() {
		return "I'm a cool Dog";
	}
	
}
原文地址:https://www.cnblogs.com/lsswudi/p/11263252.html