Object类是所有Java类的根基类,也就意味着所有的Java对象都拥有Object类的属性和方法。如果在类的声明中未使用extends关键字指明其父类,则默认继承Object类。
Object类:
public class Person { ... } //等价于: public class Person extends Object { ... }
实例:
public class TestObject { public static void main(String[] args) { // Object obj; TestObject to = new TestObject(); System.out.println(to.toString()); Person2 p2 = new Person2("张三", 6); System.out.println(p2.toString()); } public String toString(){ return "测试Object对象"; } } class Person2 { String name; int age; @Override public String toString() { return name+",年龄:"+age; } public Person2(String name, int age) { this.name = name; this.age = age; } }
运行效果: