對象類存在於java.lang包。 Java中的每個類都是直接或間接派生自對象類。如果一個類沒有擴展任何其他類,那麽它是以下類的直接子類對象如果擴展另一個類,那麽它是間接派生的。因此,Object 類方法可用於所有 Java 類。因此,Object 類充當任何 Java 程序中繼承層次結構的根。
使用對象類方法
Object類提供了多種方法,如下:
- toString()方法
- hashCode()方法
- equals(Object obj) 方法
- finalize()方法
- getClass()方法
- clone()方法
- wait()、notify() notifyAll() 方法
1.toString()方法
toString() 提供對象的字符串表示形式,用於將對象轉換為字符串。 Object 類的默認 toString() 方法返回一個字符串,其中包含該對象作為實例的類的名稱、at-sign 字符“@”以及該對象的哈希碼的無符號十六進製表示形式。換句話說,它被定義為:
// Default behavior of toString() is to print class name, then
// @, then unsigned hexadecimal representation of the hash code
// of the object
public String toString()
{
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
始終建議覆蓋toString()方法來獲取我們自己的對象的字符串表示形式。有關覆蓋 toString() 方法的更多信息,請參閱 -Overriding toString()
Note: Whenever we try to print any Object reference, then internally toString() method is called.
Student s = new Student();
// Below two statements are equivalent
System.out.println(s);
System.out.println(s.toString());
2.hashCode()方法
對於每個對象,JVM 都會生成一個唯一的數字,即哈希碼。它為不同的對象返回不同的整數。關於此方法的一個常見誤解是hashCode()方法返回對象的地址,這是不正確的。它通過算法將對象的內部地址轉換為整數。 hashCode()方法是本國的因為在Java中不可能找到對象的地址,所以它使用C/C++等原生語言來查找對象的地址。
hashCode()方法的使用
它返回一個哈希值,用於搜索集合中的對象。 JVM(Java虛擬機)使用哈希碼方法將對象保存到hashing-related數據結構中,如HashSet、HashMap、Hashtable等。基於哈希碼保存對象的主要優點是搜索變得容易。
Note: Override of hashCode() method needs to be done such that for every object we generate a unique number. For example, for a Student class, we can return the roll no. of a student from the hashCode() method as it is unique.
Java
// Java program to demonstrate working of
// hashCode() and toString()
public class Student {
static int last_roll = 100;
int roll_no;
// Constructor
Student()
{
roll_no = last_roll;
last_roll++;
}
// Overriding hashCode()
@Override public int hashCode() { return roll_no; }
// Driver code
public static void main(String args[])
{
Student s = new Student();
// Below two statements are equivalent
System.out.println(s);
System.out.println(s.toString());
}
}
輸出:
Student@64
Student@64
注意4*160+ 6*161= 100
3. equals(Object obj)方法
它將給定對象與 “this” 對象(調用該方法的對象)進行比較。它提供了一種比較對象是否相等的通用方法。建議覆蓋等於(對象 obj)方法來獲得我們自己的對象平等條件。有關重寫 equals(Object obj) 方法的更多信息,請參閱 -Overriding equals
Note: It is generally necessary to override the hashCode() method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
4.getClass()方法
它返回“this”對象的類對象,用於獲取該對象的實際運行時類。它還可用於獲取此類的元數據。返回的 Class 對象是由所表示的類的靜態同步方法鎖定的對象。由於它是最終的,所以我們不會覆蓋它。
Java
// Java program to demonstrate working of getClass()
public class Test {
public static void main(String[] args)
{
Object obj = new String("GeeksForGeeks");
Class c = obj.getClass();
System.out.println("Class of Object obj is : "
+ c.getName());
}
}
輸出:
Class of Object obj is : java.lang.String
Note: After loading a .class file, JVM will create an object of the type java.lang.Class in the Heap area. We can use this class object to get Class level information. It is widely used in Reflection
5.finalize()方法
該方法在對象被垃圾收集之前調用。它被稱為垃圾Collector當垃圾Collector確定不再有對該對象的引用時,在該對象上執行此操作。我們應該重寫 finalize() 方法來處理係統資源、執行清理活動並最大限度地減少內存泄漏。例如,在銷毀web容器的Servlet對象之前,總是調用finalize方法來執行會話的清理活動。
Note: The finalize method is called just once on an object even though that object is eligible for garbage collection multiple times.
Java
// Java program to demonstrate working of finalize()
public class Test {
public static void main(String[] args)
{
Test t = new Test();
System.out.println(t.hashCode());
t = null;
// calling garbage collector
System.gc();
System.out.println("end");
}
@Override protected void finalize()
{
System.out.println("finalize method called");
}
}
輸出:
1510467688
finalize method called
end
6.clone()方法
它返回一個與該對象完全相同的新對象。對於clone()方法請參考Clone().
其餘三種方法wait(),notify() notifyAll()與並發有關。參考Inter-thread Java 中的通信詳情。
使用 Java 中所有 Object 類方法的示例
Java
import java.io.*;
public class Book implements Cloneable {
private String title;
private String author;
private int year;
public Book(String title, String author, int year)
{
this.title = title;
this.author = author;
this.year = year;
}
// Override the toString method
@Override public String toString()
{
return title + " by " + author + " (" + year + ")";
}
// Override the equals method
@Override public boolean equals(Object obj)
{
if (obj == null || !(obj instanceof Book)) {
return false;
}
Book other = (Book)obj;
return this.title.equals(other.getTitle())
&& this.author.equals(other.getAuthor())
&& this.year == other.getYear();
}
// Override the hashCode method
@Override public int hashCode()
{
int result = 17;
result = 31 * result + title.hashCode();
result = 31 * result + author.hashCode();
result = 31 * result + year;
return result;
}
// Override the clone method
@Override public Book clone()
{
try {
return (Book)super.clone();
}
catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
// Override the finalize method
@Override protected void finalize() throws Throwable
{
System.out.println("Finalizing " + this);
}
public String getTitle() { return title; }
public String getAuthor() { return author; }
public int getYear() { return year; }
public static void main(String[] args)
{
// Create a Book object and print its details
Book book1 = new Book(
"The Hitchhiker's Guide to the Galaxy",
"Douglas Adams", 1979);
System.out.println(book1);
// Create a clone of the Book object and print its
// details
Book book2 = book1.clone();
System.out.println(book2);
// Check if the two objects are equal
System.out.println("book1 equals book2: "
+ book1.equals(book2));
// Get the hash code of the two objects
System.out.println("book1 hash code: "
+ book1.hashCode());
System.out.println("book2 hash code: "
+ book2.hashCode());
// Set book1 to null to trigger garbage collection
// and finalize method
book1 = null;
System.gc();
}
}
The Hitchhiker's Guide to the Galaxy by Douglas Adams (1979) The Hitchhiker's Guide to the Galaxy by Douglas Adams (1979) book1 equals book2: true book1 hash code: 1840214527 book2 hash code: 1840214527
相關用法
- Java Object getClass()用法及代碼示例
- Java Object hashCode()用法及代碼示例
- Java Object toString()用法及代碼示例
- Java Object equals()用法及代碼示例
- Java Object clone()用法及代碼示例
- Java Object equals(Object obj)用法及代碼示例
- Java Object finalize()用法及代碼示例
- Java ObjectInputStream readChar()用法及代碼示例
- Java ObjectInputStream readDouble()用法及代碼示例
- Java ObjectInputStream readField()用法及代碼示例
- Java ObjectInputStream readFloat()用法及代碼示例
- Java ObjectInputStream readFully()用法及代碼示例
- Java ObjectInputStream readInt()用法及代碼示例
- Java ObjectInputStream readLine()用法及代碼示例
- Java ObjectInputStream readLong()用法及代碼示例
- Java ObjectInputStream readObject()用法及代碼示例
- Java ObjectInputStream readObjectOverride()用法及代碼示例
- Java ObjectInputStream readShort()用法及代碼示例
- Java ObjectInputStream readStreamHeader()用法及代碼示例
- Java ObjectInputStream readUTF()用法及代碼示例
- Java ObjectInputStream readUnshared()用法及代碼示例
- Java ObjectInputStream readUnsingedByte()用法及代碼示例
- Java ObjectInputStream registerValidation()用法及代碼示例
- Java Objectinputstream readUnsignedShort()用法及代碼示例
- Java Objectinputstream skipBytes()用法及代碼示例
注:本文由純淨天空篩選整理自佚名大神的英文原創作品 Object Class in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。