Object源码分析(一)
Object是所有类层次结构的根,所有的类都将Object作为超类,所有的对象,包括数组,都实现了Object类的方法。
第一个方法
private static native void registerNatives();
static {
registerNatives();
}
看了博客 该方法的介绍 明白一部分,这是本地注册,调用非java语言的方法,一般是c/c++的dll文件,静态代码块就是加载本机器jdk里面的dll文件。
第二个方法:
public final native Class<?> getClass();,下面是方法注释:
/**
* Returns the runtime class of this {@code Object}. The returned
* {@code Class} object is the object that is locked by {@code
* static synchronized} methods of the represented class.
*
* <p><b>The actual result type is {@code Class<? extends |X|>}
* where {@code |X|} is the erasure of the static type of the
* expression on which {@code getClass} is called.</b> For
* example, no cast is required in this code fragment:</p>
*
* <p>
* {@code Number n = 0; }<br>
* {@code Class<? extends Number> c = n.getClass(); }
* </p>
*
* @return The {@code Class} object that represents the runtime
* class of this object.
* @jls 15.8.2 Class Literals
*/
由注释可以知道该类表示java应用实际运行时的类。
例子:
public class demo implements Idemo {
public static void main(String[] args) {
demo d=new demo();
Idemo idemo=new demo();
Class<? extends demo> aClass = d.getClass();
Class<? extends Idemo> aClass1 = idemo.getClass();
System.out.println("实现类 "+aClass);
System.out.println("接口-"+aClass1);
}
}
运行结果
第三个方法
public native int hashCode();
这个方法返回对象的哈希码值,这个方法与哈希表的性能有关,它的实现方法是通过将对象在内存中所处于的位置转换成数字,这个数字就是hashCode。但是这个内存地址实际上java程序并不关心也是不可知的。这个地址是由JVM维护并保存的,所以实现是native的。通用的约定是:
(1)在同个java环境下,相同的对象必须有同样的哈希码值;但是对于这个具体的整数值(哈希码)在两个相同应用下不需要一定要保持一致(后期会学到如何构建哈希表,一个对象在不同的哈希表下会有不同的哈希值)。
(2)如果两个对象通过equals方法是相等的,则他们的哈希值相同。
(3)反过来,如果两个对象通过equals方法是不相等的,他们的哈希值不一定不同。但是开发者应该明白,对于不相等的两个对象返回不同的哈希值会提高哈希表的性能。
该方法与java.lang.System下的identityHashCode方法作用相同
第四个方法
public boolean equals(Object obj) {
return (this == obj);
}
判断其它对象是否与此对象“相等 ”;如果一个对象要重写这个方法,需要与其它非空对象满足等价关系:以下的x,y,z均为非空对象
(1)自反性,x.equals(x)=true;
(2)对称性,x.equals(y) = y.equals(x);
(3)传递性,若x.equals(y) = true,y.equals(z) = true,则x.equals(z) = true;
(4)一致性,只要equals的比较操作在对象中所用的信息没有被修改,多次调用x.equals(y)就会一致地返回相同结果;
(5)x.equals(null) = false;
注意: 当重写equals方法时,也要重写hashCode方法,这是为了确保相等的对象有相同的哈希码值。使用eclipse或者IDEA的自动生成。
public class Cat {
private String name;
private String age;
public Cat() {
}
public Cat(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Cat cat = (Cat) o;
return Objects.equals(name, cat.name) &&
Objects.equals(age, cat.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}