Object类是所有java类的基类,也就意味着java所有类都有Object类的属性和方法。
package com.bjsxt.test;
public class TestToString {
public static void main(String[] args) {
TestToString tts=new TestToString();
System.out.println(tts.toString());
Person2 p2=new Person2("梨花", 15);
System.out.println(p2.toString());
}
public String toString(){
return "测试toString()重写";
}
}
class Person2{
String name;
int age;
public Person2(String name,int age) {
this.age=age;
this.name=name;
}
@Override
public String toString(){
return name+",年龄:"+age;
}
}