你们看到这个标题的时候,肯定在骂我,什么类这么厉害?使用率100%?其实我不是标题党,本篇文章给大家介绍的就是JDK中所有类的父类——java.lang.Object,你说使用率不是100%,我想任何类都逃不掉吧。
Object 类属于 java.lang 包,此包下的所有类在使用时无需手动导入,系统会在程序编译期间自动导入。Object 类是所有类的基类,当一个类没有直接继承某个类时,默认继承Object类,也就是说任何类都直接或间接继承此类,Object 类中能访问的方法在所有类中都可以调用,下面我们会分别介绍Object 类中的所有方法。
1、Object 类的结构图
Object.class类
/*
* Copyright (c) 1994, 2012, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*/
package java.lang;
/**
* 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 JDK1.0
*/
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
public final native Class<?> getClass();
public native int hashCode();
public boolean equals(Object obj) {
return (this == obj);
}
protected native Object clone() throws CloneNotSupportedException;
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
public final native void notify();
public final native void notifyAll();
public final native void wait(long timeout) throws InterruptedException;
public final void wait(long timeout, int nanos) throws InterruptedException {
if (timeout < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos > 0) {
timeout++;
}
wait(timeout);
}
public final void wait() throws InterruptedException {
wait(0);
}
protected void finalize() throws Throwable { }
}
2、 为什么java.lang包下的类不需要手动导入?
不知道大家注意到没,我们在使用诸如Date类时,需要手动导入import java.util.Date,再比如使用File类时,也需要手动导入import java.io.File。但是我们在使用Object类,String 类,Integer类等不需要手动导入,而能直接使用,这是为什么呢?
这里先告诉大家一个结论:使用 java.lang 包下的所有类,都不需要手动导入。
另外我们介绍一下Java中的两种导包形式,导包有两种方法:
①、单类型导入(single-type-import),例如import java.util.Date
②、按需类型导入(type-import-on-demand),例如import java.util.*
单类型导入比较好理解,我们编程所使用的各种工具默认都是按照单类型导包的,需要什么类便导入什么类,这种方式是导入指定的public类或者接口;
按需类型导入,比如 import java.util.*,可能看到后面的 *,大家会以为是导入java.util包下的所有类,其实并不是这样,我们根据名字按需导入要知道它是按照需求导入,并不是导入整个包下的所有类。
Java编译器会从启动目录(bootstrap),扩展目录(extension)和用户类路径下去定位需要导入的类,而这些目录仅仅是给出了类的顶层目录,编译器的类文件定位方法大致可以理解为如下公式:
顶层路径名 \ 包名 \ 文件名.class = 绝对路径
单类型导入我们知道包名和文件名,所以编译器可以一次性查找定位到所要的类文件。按需类型导入则比较复杂,编译器会把包名和文件名进行排列组合,然后对所有的可能性进行类文件查找定位。例如:
package com;
import java.io.*;
import java.util.*;
如果我们文件中使用到了 File 类,那么编译器会根据如下几个步骤来进行查找 File 类:
①、File // File类属于无名包,就是说File类没有package语句,编译器会首先搜索无名包
②、com.File // File类属于当前包,就是我们当前编译类的包路径
③、java.lang.File //由于编译器会自动导入java.lang包,所以也会从该包下查找
④、java.io.File
⑤