在 Java 中,所有类都直接或间接地继承自 Object
类。Object
类提供了一些通用的方法,这些方法可以被所有对象使用。
以下是 Object
类的一些重要方法:
1. toString()
String toString();
得到类名和哈希码
//演示
package object;
public class Object {
public static void main(String[] args) {
Object object=new Object();
System.out.println(object.toString());///结果 object.Object@2f92e0f4,
}
}
返回对象的字符串表示。默认情况下,返回的字符串包含类名和对象的哈希码。
2、getClass()
Class<?> getClass();
class Person {
// ...
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.getClass()); // 输出: class Person
}
}
返回对象的运行时类。
3. hashCode()
int hashCode();
package object;
public class Hash {
public static void main(String[] args) {
Object object=new Object();
System.out.println(object.hashCode());
}
}
返回对象的哈希码。默认情况下,返回对象的内部地址。
4. equals(Object obj)
boolean equals(Object obj);
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 重写 equals 方法,根据对象的内容比较相等性
@Override
public boolean equals(Object obj) {
// 自反性检查,即对象与自身比较返回 true
if (this == obj) {
return true;
}
// 类型检查,确保比较的对象是当前类的实例
if (obj == null || getClass() != obj.getClass()) {
return false;
}
// 强制类型转换
Person person = (Person) obj;
// 根据对象的内容比较相等性
return age == person.age && name.equals(person.name);
}
public static void main(String[] args) {
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Alice", 25);
Person person3 = new Person("Bob", 30);
// 使用重写的 equals 方法进行比较
System.out.println(person1.equals(person2)); // 输出: true
System.out.println(person1.equals(person3)); // 输出: false
}
}
5. finalize()
protected void finalize() throws Throwable;
在对象被垃圾回收之前调用。
这些方法是 Object
类中的一部分,它们在所有 Java 对象中都可用。在实际编程中,你可以根据需要覆盖其中的某些方法,以适应你的类的特定需求。
5. clone()
protected Object clone() throws CloneNotSupportedException;
class MyClass implements Cloneable {
int value;
public MyClass(int value) {
this.value = value;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Main {
public static void main(String[] args) {
MyClass original = new MyClass(42);
try {
// 使用clone()方法创建对象的拷贝
MyClass copy = (MyClass) original.clone();
System.out.println(copy.value); // 输出: 42
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
用于创建并返回一个对象的拷贝,即克隆对象。在使用 clone()
方法时,被克隆的类必须实现 Cloneable
接口,否则会抛出 CloneNotSupportedException
异常。
除此之外还有很多方法
notify()、
唤醒在对象上等待的单个线程。如果有多个线程在该对象上等待,只会唤醒其中一个。
notifyAll()
唤醒在对象上等待的所有线程。
wait()
导致当前线程等待,直到其他线程调用该对象的 notify()
或 notifyAll()
方法,或者指定的时间过去。