Object
1. 超类、基类、所有类的直接或间接继承父类,位于继承树的最顶层。
2. 任何类,如没有书写extends显示继承某个类,都默认直接继承Object类,否则为间接继承。
3. Object类中所定义的方法,是所有对象都具备的方法。
4. Object类型可以储存任何对象。作为参数,可接受任何对象。作为返回值,可返回任何对象。
1. getClass()
返回一个Class类型
1. public final Class<?> getClass(){}
2. 返回引用中存储的实际对象类型。
3. 应用:通常用于判断两个引用中实际存储对象类型是否一致。
package com.studyObject.Demo01;
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student("aa",20);
Student s2 = new Student("bb",21);
// 判断s1和s2是不是同一个类型
Class class1 = s1.getClass();
Class class2 = s2.getClass();
System.out.println(class1 == class2);
}
}
2. hashCode()
返回一个int类型的哈希码值
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
3. toString()
1. public String toString(){}
2. 返回该对象的字符串表示(变现形式)。
3. 可以根据程序需求覆盖该方法,如:展示对象各个属性值。
System.out.println(s1.toString());
System.out.println(s2.toString());
4. equals()
1. public boolean equals(Object obj){}
2. 默认实现方法为(this==obj),比较两个对象的地址是否相同。
3. 可进行覆盖,比较两个对象的内容是否相同。
equals方法的重写
@Override
public boolean equals(Object o) {
// 判断两个对象是不是同一个引用
if(this == o) return true;
// 判断 o 是不是为空
if(o == null) return false;
// 是不是同一个类型
if(o instanceof Student){
// 强制类型转换
Student s =(Student) o;
// 比较属性
if((this.name.equals(s.getName()))&&(this.age == s.getAge())){
return true;
}else{
return false;
}
}
return false;
}
使用:
Student s5 = new Student("小敏", 2);
Student s6 = new Student("小敏", 2);
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s5.equals(s6));
5.finalize
1. 当对象被判定为垃圾对象时,由JVM自动调用此方法,用以标记垃圾对象,进入回收队列。
2. 垃圾对象:没有有效引用指向此对象时,为垃圾对象。
3. 垃圾回收:由GC销毁垃圾对象,释放数据存储空间。
4. 自动回收机制:JVM的内存耗尽,一次性回收所有垃圾对象。
5. 手动回收机制:使用System.gc();通知JVM执行垃圾回收。
new Student("x",2);
System.gc();
System.out.println("回收垃圾");