Object是java默认提供的类
java除了Object类,所有的类都存在继承关系,默认会继承Object父类,所以所有类对象都可以通过Object类进行接收(向上转型)
class A {}
class B {}
public class Test {
public static void main(String[] args) throws Exception {
test(new A());
test(new B());
}
public static void test(Object obj) {
System.out.println(obj);
}
}
取得对象信息—toString()
class Person {
private String name;
private int age;
public Person(String name,int age) {
this.name = name;
this.age = age;
}
}
public class Test {
public static void main(String[] args) throws Exception {
test(new Person("张三",20));
test("hello");
}
public static void test(Object obj) {
System.out.println(obj);
}
}
class Person {
private String name;
private int age;
public Person(String name,int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "姓名:"+this.name+", 年龄:"+this.age;
}
}
public class Test {
public static void main(String[] args) throws Exception {
test(new Person("张三",20));
test("hello");
}
public static void test(Object obj) {
System.out.println(obj.toString());
}
}
对象比较—equals()
class Person {
private String name;
private int age;
public Person(String name,int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "姓名:"+this.name+", 年龄:"+this.age;
}
}
public class Test {
public static void main(String[] args) throws Exception {
Person per1 = new Person("你好,中国",100);
Person per2 = new Person("你好,中国",100);
System.out.println(per1.equals(per2)); // false
}
}
比较的还是对象地址,如果要比较属性内容,需要覆写equals
class Person {
private String name;
private int age;
public Person(String name,int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "姓名:"+this.name+", 年龄:"+this.age;
}
public boolean equals(Object obj) {
// 判断obj是否是Person实例
if(!(obj instanceof Person))
return false;
if(obj == this)
return true;
// 向下转型,取得Perso类的其他属性
Person per = (Person) obj;
return per.name.equals(this.name) && (per.age == this.age);
}
}
接收引用数据类型
Object可以接收所有引用类型,包括:类、数组、接口
public class Test {
public static void main(String[] args) throws Exception {
// Object接收数组对象,向上转型
Object obj = new int[]{1,3,5,7,9};
// 向下转型,需要强转
int[] data = (int[]) obj;
for(int i : data)
System.out.print(i+"、");
}
}
Object可以接收接口是Java中的强制要求,因为接口本身不能继承任何类。
interface IMessage {
void getMessage();
}
class MessageImpl implements IMessage {
public String toString() {
return "你好中国!!!";
}
public void getMessage() {
System.out.println("hello world");
}
}
public class Test {
public static void main(String[] args) throws Exception {
IMessage msg = new MessageImpl();
Object obj = msg;
System.out.println(obj);
IMessage temp = (IMessage) obj;
temp.getMessage();
}
}