Object 类型可以存储任何对象
作为参数,可接受任何对象
作为返回值,可返回任何对象
clone() 浅拷贝,一般深拷贝,彻底深拷贝
wait(), notify() 对象间通信与协同
public final native Class<?> getClass();
返回引用中存储的实际对象类型
应用:判断两个引用中实际存储对象类型是否一致
Person person = new Person();
Person person2 = new Person();
System.out.println(person.getClass() == person2.getClass()); // true
public native int hashCode();
返回该对象的哈希码值
哈希值是根据对象的地址或字符串或数字,使用 hash 算法计算出来的 int 类型的数值
一般情况下相同对象返回相同哈希码
System.out.println(person.hashCode());
System.out.println(person2.hashCode());
Person person3 = person;
person.hashCode() == person3.hashCode();
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
一般会根据需求重写该方法
public boolean equals(Object obj) {
return (this == obj);
}
person.equals(person2) // false
默认实现 this == obj,比较两个对象地址是否相同
关于 == 与 equals
当对象被判定为垃圾对象时,由 JVM 自动调用此方法,用以标记垃圾对象,进入回收队列
对象销毁
自动回收机制:JVM 的内存耗尽,一次性回收所有垃圾对象
手动回收机制:使用 System.gc(); 通知 JVM 执行垃圾回收
public class Demo {
/**
* java提供finalize()方法,垃圾回收器准备释放内存的时候,会先调用finalize()
* @throws Throwable
*/
@Override
protected void finalize() throws Throwable {
System.out.println("finalize");
}
}
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
@Override
protected void finalize() throws Throwable {
System.out.println(this.name + "对象被回收");
// super.finalize();
}
}
Person person = new Person("aaa");
new Person("bbb"); // 此对象未被引用,会被回收
System.gc();
System.out.println("======");
// result
======
bbb对象被回收