当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Object用法及代码示例


对象类存在于java.lang包。 Java中的每个类都是直接或间接派生自对象类。如果一个类没有扩展任何其他类,那么它是以下类的直接子类对象如果扩展另一个类,那么它是间接派生的。因此,Object 类方法可用于所有 Java 类。因此,Object 类充当任何 Java 程序中继承层次结构的根。

Object Class in 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



相关用法


注:本文由纯净天空筛选整理自佚名大神的英文原创作品 Object Class in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。