Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ทำไม Object class จึงเป็น Super class สำหรับทุกคลาสใน Java?

Java.lang.Object class เป็น root หรือ superclass ของ class hierarchy ซึ่งอยู่ใน java.lang package ทุก predefined classes และ user-defined classes เป็น subclasses ของ Object class

ทำไม Object class ถึงเป็น superclass

Re-usability (ความสามารถในการนำกลับมาใช้ใหม่)

  • ทุก object มี 11 common properties ทุก Java developer ต้อง implement properties เหล่านี้
  • เพื่อลดภาระของ developer SUN พัฒนาคลาสชื่อ Object โดย implement ทั้ง 11 properties ด้วย 11 methods
  • เมธอดทั้งหมดมี generic logic ที่ common สำหรับทุก subclasses หาก logic นี้ไม่ตอบสนองความต้องการของ subclass subclass สามารถ override ได้

Runtime polymorphism

  • เพื่อให้บรรลุ runtime polymorphism เพื่อให้เราเขียน single method เพื่อรับและส่ง object ของทุกประเภทของคลาสเป็น argument และ return type ได้

Common functionalities ของทุก class object

เปรียบเทียบสองออบเจ็กต์

  • public boolean equals(Object obj)

ดึง hashcode

  • public int hashcode()

ดึง run time class object reference

  • public final Class getClass()

ดึงข้อมูลออบเจ็กต์ในรูป String format

  • public String toString()

Clone object

  • protected Object clone() throws CloneNotSupportedException

Object clean-up code / resources releasing code

  • protected void finalize() throws Throwable

รอ current thread จนกว่า thread อื่นจะ invoke notify()

  • public final void wait() throws InterruptedException

รอ current thread จนกว่า thread อื่นจะ invoke notify() ภายในเวลาที่กำหนด

  • public final void wait(long timeout) throws InterruptedException

รอ current thread จนกว่า thread อื่นจะ invoke notify() ภายในเวลาที่กำหนด

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

แจ้งเตือนเรื่อง object lock availability ให้ waiting thread

  • public final void notify()

แจ้งเตือนเรื่อง object lock availability ให้ waiting threads

  • public final void notifyAll()

ตัวอย่าง

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
    }
}

ผลลัพธ์

This is: Adithya