常用類Object,String類詳解
阿新 • • 發佈:2019-03-03
ash trace native object類 obj 關鍵字 圖片 sys img
深拷貝
淺拷貝
垃圾回收
package com.demo.obj; /** * 學習Object類 * native 本地棧方法, 方法使用使用c語言中實現的方法 * hashcode 就是一個對象在內存中地址 * toString * clone * equals * finalize * @author Administrator * * // 再次強調靜態方法中不能使用this關鍵字 * */ public class ObjectTest extends Object implements Cloneable {public static void main(String[] args) { // 創建一個對象 ObjectTest obj = new ObjectTest(); // 使用System.out.println打印一個對象的時候會自動調用該對象的toString()方法 System.out.println(obj); // @15db9742 // 使用hashcode方法 System.out.println(Integer.toHexString(obj.hashCode()));// 使用toString方法 // System.out.println(obj.toString()); Object obj1 = obj.cloneObject(); System.out.println(obj1); // @6d06d69c Object obj3 = obj; // equals方法 (==) 比較2個對象的引用(內存地址)是否相同 System.out.println(obj == obj1); // false 內存地址不同 System.out.println(obj3 == obj); //true 內存地址相同 System.out.println(obj.equals(obj1)); System.out.println(obj3.equals(obj)); // obj1=null; System.gc(); // 手動調用系統中的垃圾回收器 // 需要使用垃圾回收觸發finalize調用 } @Override protected void finalize() throws Throwable { System.out.println("== 對象的銷毀 =="); super.finalize(); // 調用父類中gc回收對象的時候就會調用 } //@Override // 重寫了父類中toString()方法 /*public String toString() { return "ObjectTest []"; }*/ public Object cloneObject() { Object obj = null; try { // java.lang.CloneNotSupportedException: com.demo.obj.ObjectTest // 必須實現Cloneable接口 obj = this.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return obj; } }
常用類Object,String類詳解