Java - Object class (basic)

Object class

Object class is a top-level parent of all classes, classes are run by directly or indirectly inherit from it.

public class myTest01 {
    public static void main(String[] args){
        Object o = new Object();
        //object中的方法。
        System.out.println(o.hashCode());//返回此对象的一个hash值
        System.out.println(o.toString());//返回一个字符串,该字符串由类名(对象是该类的一个实例)、at 标记符“@”和此对象哈希码的无符号十六进制表示组成。通俗理解获取该类的字节码文件对象。
        System.out.println(o.getClass());//表示此对象运行时类的 Class 对象。
    }
}

Method Object class clone

  //Object中的原方法实现。
  protected native Object clone() throws CloneNotSupportedException;
  //首先克隆方法的修饰词是protected的所以在继承Object类的时候,想要使用这个方法必须近行继承重写
  class test{
    String str = "hello";
    @Override
    //重写时将权限修饰词改为public
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    //因为native修饰的源码是JVM底层所交互,这里我们看不到源码。所以不能重写里边所拥有的方法
    //方法重写后在调用这个方法的时候,必须要捕获编译异常。
}

Object of the
shallow clone: clone is an object, the object is cloned inside a subject in another class. This time is just another object clones address value, without the additional object is also a clone.

public class myTest01 {
    public static void main(String[] args) throws CloneNotSupportedException {
		//捕获编译异常后才能使用此方法。
        test test = new test();
        Object clone = test.clone();
    }
}
class test{
    String str = "hello";
    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

equals method of Object

The actual ratio equals method is to heap memory in the address, but in the actual process we use is the ratio of the value of some type, rather than the memory address is, for some reason often overridden methods.

//定义一个实例方法
class test{
	String str;
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        test test = (test) o;
        return Objects.equals(str, test.str);
    }
}

Object toString method override in

Should have been printed memory address value is generally a lot of class overrides the toString method, let the value of the variable printing members.

class test{
    String str = "hello";

    @Override
    public String toString() {
        return "test{" +
                "str='" + str + '\'' +
                '}';//重写后的toString方法,打印出来的就是字符串成员变量值。可以根据自己的需求重写。
    }
}
Published 15 original articles · won praise 8 · views 10000 +

Guess you like

Origin blog.csdn.net/Junzizhiai/article/details/102574436