java.lang Object:是每一个类的根类,每个类都直接或间接的继承Object类。
子类的构造方法默认访问的是父类的无参构造方法
public int hashCode():返回该对象的哈希码值。哈希值是根据哈希算法计算出来的一个值。这个值和地址值有关,但不是实际地址值。
// 对象不同,哈希值一般也不同
Student s1 = new Student();
System.out.println(s1.hashCode()); // 366712642
Student s2 = new Student();
System.out.println(s2.hashCode()); // 1829164700
System.out.println("-------");
public final Class getClass():返回Object运行时类。也就是说是字节码文件对象。
// getClass方法会返回一个Class类的实例对象,然后调用Class类的getName()方法
Student s = new Student();
System.out.println(s.getClass().getName()); // org.danni.objectdemo.Student(返回全路径名)
public String toString():
Object 类的 toString 方法返回一个字符串,该字符串由类名(对象是该类的一个实例)、at 标记符“@”和此对象哈希码的无符号十六进制表示组成。换句话说,该方法返回一个字符串,它的值等于: getClass().getName() + ‘@’ + Integer.toHexString(hashCode())
// toString方法:返回对象的字符串表示
System.out.println(s.toString()); // org.danni.objectdemo.Student@7852e922
//直接输出对象的名称其实就是调用了对象的toString方法
System.out.println(s); //org.danni.objectdemo.Student@7852e922
public boolean equals(Object obj):只是其他某个对象与此对象是否 “相等”
Object中equals方法的源码:
/*
==:
基本类型:比较的就是值是否相同
引用类型:比较的是地址值是否相同
*/
Student s1 = new Student(); //自己定义一个Student类。
Student s2 = new Student();
System.out.println(s1 == s2); //false
Student s3 = s1;
System.out.println(s3 == s1); //true
System.out.println(s1.equals(s2)); //false
System.out.println(s1.equals(s1)); //true
System.out.println(s1.equals(s3)); //true
equals方法默认情况下比较的是地址值,但是比较地址值一般来说意义不大,所以,通常情况下我们会重写equals方法。一般都是用来比较对象的成员变量值是否相同。
String的equals方法是重写了Object的equals方法的,它比较的是字符串的值。
protected void finalize():当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法,用于垃圾回收。但是具体什么时间调用此方法不确定。
protected Object clone():创建并返回此对象的一个副本。需要重写该方法
1、要克隆的类去实现Cloneable接口
2、并重写Cloneable方法
2、Cloneable接口是标记接口,实现该接口的类就可以实现对象的复制。
Student类:
public class Student implements Cloneable{
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
测试类:
public class StudentTest{
public static void main(String[] args) throws CloneNotSupportedException {
// 创建显示对象
Student s = new Student();
s.setName("hehe");
s.setAge(23);
// 克隆学生对象
Student cloneStudent = (Student) s.clone();
//引用
Student s2 = s;
System.out.println(s.getName()+","+s.getAge()); //hehe,23
System.out.println(cloneStudent.getName()+","+cloneStudent.getAge()); //hehe,23
System.out.println(s2.getName()+","+s2.getAge()); //hehe,23
s2.setAge(18);
s2.setName("变了");
System.out.println(s.getName()+","+s.getAge()); //变了,18
System.out.println(cloneStudent.getName()+","+cloneStudent.getAge()); //hehe,23(克隆的对象不会跟着改变)
System.out.println(s2.getName()+","+s2.getAge()); //变了,18
}
}