Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Tại sao Object class là super class cho tất cả các class trong Java?


Java.lang.Object class là root hoặc superclass của hệ thống phân cấp class, nằm trong java.lang package. Tất cả predefined classes và user-defined classes đều là subclass từ Object class.

Tại sao object class là superclass

Tái sử dụng (Re-usability)

  • Mọi object có 11 common properties, các properties này phải được implement bởi mọi Java developer.
  • Để giảm gánh cho developer, SUN phát triển class Object bằng cách implement tất cả 11 properties này với 11 methods.
  • Tất cả các methods này có logic chung cho tất cả subclass, nếu logic này không thỏa mãn yêu cầu subclass thì subclass có thể override nó

Runtime polymorphism

  • Để đạt runtime polymorphism để có thể viết single method nhận và gửi bất kỳ loại class object nào làm tham số và return type.

Các chức năng chung của mọi class object

So sánh hai object

  • public boolean equals(Object obj)

Lấy hashcode

  • public int hashcode()

Lấy run time class object reference

  • public final Class getClass()

Lấy thông tin object dạng String

  • public String toString()

Clone object

  • protected Object clone() throws CloneNotSupportedException

Dọn dẹp object/ giải phóng tài nguyên

  • protected void finalize() throws Throwable

Đợi current thread cho đến khi thread khác invoke notify()

  • public final void wait() throws InterruptedException

Đợi current thread cho đến khi thread khác invoke notify() trong thời gian xác định

  • public final void wait(long timeout) throws InterruptedException

Đợi current thread cho đến khi thread khác invoke notify() trong thời gian xác định

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

Thông báo về object lock availability cho waiting thread

  • public final void notify()

Thông báo về object lock availability cho waiting threads

  • public final void notifyAll()

Ví dụ

class Thing extends Object implements Cloneable { 
    public String id; 
    public Object clone() throws CloneNotSupportedException { 
        return super.clone(); 
    } 
    public boolean equals(Object obj) { 
        boolean result = false; 
        if ((obj!=null) && obj instanceof Thing) { 
            Thing t = (Thing) obj; 
            if (id.equals(t.id)) result = true; 
        } 
        return result; 
    } 
    public int hashCode() { 
        return id.hashCode(); 
    } 
    public String toString() { 
        return "This is: "+id; 
    } 
} 
public class Test { 
    public static void main(String args[]) throws Exception { 
        Thing t1 = new Thing(), t2; 
        t1.id = "Raj"; 
        t2 = t1; // t1 == t2 and t1.equals(t2) 
        t2 = (Thing) t1.clone(); // t2!=t1 but t1.equals(t2) 
        t2.id = "Adithya"; // t2!=t1 and !t1.equals(t2) 
        Object obj = t2; 
        System.out.println(obj); //Thing = Adithya 
    } 
}

Kết quả

This is: Adithya