1.什么是Object类?
继承者称作子类也叫派生类,被继承者称作父类、基类或超类,objec类是所有类的父类。
Object类是所有Java类的祖先。每个类都使用 Object 作为超类。所有对象(包括数组)都实现这个类的方法。
同时,在不明确给出超类的情况下,Java会自动把Object类作为要定义类的超类,可以使用类型为Object的变量指向任意类型的对象。
Object类有一个默认构造方法pubilc Object(),在构造子类实例时,都会先调用这个默认构造方法。Object类的变量只能用作各种值的通用持有者。要对他们进行任何专门的操作,都需要知道它们的原始类型并进行类型转换。
2.查看object类
1.首先,点击进入lib文件夹
2.依次点击src.zip进入JAVA原源码的压缩包,点击Java.base
点击Java.base 文件
lang文件
之后搜索object.java文件,之后我们可以看到
/**
* Class {@code Object} is the root of the class hierarchy.
* Every class has {@code Object} as a superclass. All objects,
* including arrays, implement the methods of this class.
*
* @author unascribed
* @see java.lang.Class
* @since 1.0
*/
翻译过来为:
/**
* 类 {@code 对象} 是类层次结构的根。
* 每个类都有 {@code Object} 作为超类。所有对象,
* 包括数组,实现此类的方法。
*
* @author未注明出处
* @see java.lang.class
* @since 1.0
*/
3.有关objec类存在的方法
package java.lang;
import jdk.internal.HotSpotIntrinsicCandidate;
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
@HotSpotIntrinsicCandidate
public Object() {}
@HotSpotIntrinsicCandidate
public final native Class<?> getClass();
@HotSpotIntrinsicCandidate
public native int hashCode();
public boolean equals(Object obj) {
return (this == obj);
}
@HotSpotIntrinsicCandidate
protected native Object clone() throws CloneNotSupportedException;
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
@HotSpotIntrinsicCandidate
public final native void notify();
@HotSpotIntrinsicCandidate
public final native void notifyAll();
public final void wait() throws InterruptedException {
wait(0L);
}
public final native void wait(long timeoutMillis) throws InterruptedException;
public final void wait(long timeoutMillis, int nanos) throws InterruptedException {
if (timeoutMillis < 0) {
throw new IllegalArgumentException("timeoutMillis value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos > 0 && timeoutMillis < Long.MAX_VALUE) {
timeoutMillis++;
}
wait(timeoutMillis);
}
@Deprecated(since="9")
protected void finalize() throws Throwable { }
}
对于以下代码
private static native void registerNatives();
此方法以 ";"结尾,同时修饰符列表带有“native ”关键字
表示底层调用C++写的dll程序(dll动态链接库文件)
4.toString方法的测试
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
测试1
1.创建一个类
class Product{
}
因为Product默认继承object类
2.创建对象,并通过引用去输出
public class test {
public static void main(String[] arge){
Product pro=new Product();
String ret=pro.toString();
System.out.println(ret);
}
}
运行之后显示
其中54bedef2等同于是对象在内存当中的内存地址,而实际上是内存地址经过“哈希算法”得出的。
2.测试2
1.还是创建一个类,默认继承object
class Product{
}
2.
public class test {
public static void main(String[] arge){
Product pro=new Product();
System.out.println(pro);
}
}
这次我们直接输出一个引用时,运行结果为
我们可知,当println直接输出一个引用时,会默认输出调用toString方法。
return getClass().getName() + "@" + Integer.toHexString(hashCode());