Object类是Java中所有类的始祖,最高层的超类。在新建一个类时候,如果没有明确的指出超类,Object就是他的超类,并且无需显式的extends。
- Object类中的方法
Modifier and Type | Method | Description |
---|---|---|
protected Object | clone() | 创建并返回此对象的副本。 |
boolean | equals(Object obj) | 指示一些其他对象是否等于此。 |
protected void | finalize() | 当垃圾收集确定不再有对该对象的引用时,垃圾收集器在对象上调用该对象。 |
类<?> | getClass() | 返回此 Object的运行时类。 |
int | hashCode() | 返回对象的哈希码值。 |
void | notify() | 唤醒正在等待对象监视器的单个线程。 |
void | notifyAll() | 唤醒正在等待对象监视器的所有线程。 |
String | toString() | 返回对象的字符串表示形式。 |
void | wait() | 导致当前线程等待,直到另一个线程调用该对象的 notify()方法或 notifyAll()方法。 |
void | wait(long timeout) | 导致当前线程等待,直到另一个线程调用 notify()方法或该对象的 notifyAll()方法,或者指定的时间已过。 |
其中toString()方法和equals()方法非常常用。
toString()方法
我们先创建一个People类
public class People {
private String name;
private int age;
public People(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
所有的类都是Object类的子类,所以所有的类都可以使用toString()方法。
public class Main {
public static void main(String[] args) {
People people = new People("张三", 18);
System.out.println(people.toString());
}
}
直接调用toString()方法是没有结果的,需要输出打印出来。
结果是一个地址值:
在People类中可以重写toString()方法
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
重写之后的输出:
有的类会将toString()方法重写,比如ArrayList类
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> array = new ArrayList<>(10);
array.add("abc");
array.add("xxx");
System.out.println(array.toString());
}
}
当想确定toString()方法是否被重写时,只需要将该对象的toString()输出即可,如果是地址,则没有被重写。
equals()方法
equals()方法默认比较两者的地址值是否相同,所以如果没有重写equals()方法就使用可能不会出现期待出现的答案:
public class Main {
public static void main(String[] args) {
People people1 = new People("张三", 18);
People people2 = new People("张三", 18);
System.out.println(people1.equals(people2));
}
}
运行结果:
重写equals()方法:
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
People people = (People) o;
return age == people.age &&
Objects.equals(name, people.name);
}
运行结果: