• 源码学习-Object类


    1.Object类是Java所有类的超类

    2.查看Object的属性和方法,发现Object类没有属性,只有13个方法,其中7个本地方法。

      

    3.接下来看具体的方法

    3.1 Object() 默认的构造方法

    3.2 registerNatives() 注册所有的本地方法

    方法签名:

    private static native void registerNatives()

    这个方法是一个本地方法,用来注册本类中所有的本地方法。权限为私有,在类中有一个静态代码块调用  

    static {
            registerNatives();
        }

    3.3 getClass() 返回一个对象的运行时类对象,本地方法

    方法签名:

    public final native Class<?> getClass();

    3.4 hashCode() 返回对象的HashCode,本地方法

    方法签名:

    public native int hashCode();

    3.4.1 HashCode用于散列存储结构(如Hashtable,HashMap)中确定对象存储地址,利于查找快捷性

    3.5 equals(Object obj) 判断两个对象是否相等

    public boolean equals(Object obj) {
            return (this == obj);
        }

    3.5.1 如果两个对象的equals为true,那么这两个对象的hashCode一定相等,反之,如果两个对象的hashCode相同,两个对象的equals不一定为true,只能说明他们存放在散列存储结构中的地址相同。

    3.5.2 重写类的equals方法要同时重写hashCode方法,并遵守3.5.1的原则

    重写例子:假设有一个User类,有String username,和String id,只要id相等就代表是同一个User

    public boolean equals(Object obj) {
            if(this == obj) return true;
            if(obj instanceof User){
                  if(this.id.equals(((User)obj).getId()){
                      return true;
                  }
             }
            return false;
        }

    重写User类的HashCode方法例子

    public int hashCode(){
        int result = 29;
        return this.id.hashCode()*result;
    
    }

    3.6 clone() 克隆对象,可以克隆的对象的类必须要实现Cloneable接口

    方法签名:

    protected native Object clone() throws CloneNotSupportedException;

    3.7 toString() 返回能代表一个对象的字符串(类名+16进制的HashCode)

    public String toString() {
            return getClass().getName() + "@" + Integer.toHexString(hashCode());
        }

    3.8 notify()

    public final native void notify();

    3.9 notifyAll()

    public final native void notifyAll();

    3.10 wait(long timeout)

    public final native void wait(long timeout) throws InterruptedException;

    3.11 wait(long timeout, int nanos) 本质上调用的是本地方法wait(long timeout)

    public final void wait(long timeout, int nanos) throws InterruptedException

    3.12 wait()

    public final void wait() throws InterruptedException {
            wait(0);
        }

      3.8到3.12都是多线程相关的,调用对象的wait时会挂起调用这个方法的线程,直到调用对象的notify或者notifyAll的同步块执行完毕,然而同步块执行完毕之后运行的是哪个线程决定于JVM的调度策略,而不是说之前调用wait挂起的线程一定会执行。

    3.13 finalize() 空方法,与JVM垃圾回收机制有关,JVM准备对此对象所占用的内存空间进行垃圾回收前,将被调用。主动调用此方法并不会有什么效果。

    protected void finalize() throws Throwable { }
  • 相关阅读:
    jquery.validate使用攻略 5
    jquery.validate使用攻略 4
    ccnet1.5集成tfs中文版的问题
    解决mysql连接异常—com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception
    Myeclipse 6.5 增加对 JavaEE 6 的支持
    Python3.7环境配置
    myeclipse 8.6 software and workspace center is currently not available
    入坑cordova
    开启博客之路
    如何在高并发的分布式系统中产生UUID
  • 原文地址:https://www.cnblogs.com/cici20166/p/6295326.html
Copyright © 2020-2023  润新知