为什么Object类是Java中所有类的超类?


Java.lang.Object 类是类层次结构的根或超类,它位于java.lang包中。所有预定义类和用户定义类都是Object类的子类。

为什么Object类是超类

可重用性

  • 每个对象都有11个共同属性,这些属性必须由每个Java开发人员实现。
  • 为了减轻开发人员的负担,SUN开发了一个名为Object的类,它用11个方法实现了这11个属性。
  • 所有这些方法都具有对所有子类通用的逻辑,如果此逻辑不满足子类的需求,则子类可以覆盖它。

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

运行时多态性

  • 为了实现运行时多态性,以便我们可以编写单个方法来接收和发送任何类型的类对象作为参数和返回类型。

每个类对象的通用功能

比较两个对象

  • public boolean equals(Object obj)

获取哈希码

  • public int hashCode()

检索运行时类对象引用

  • public final Class getClass()

以字符串格式检索对象信息

  • public String toString()

克隆对象

  • protected Object clone() throws CloneNotSupportedException

对象清理代码/资源释放代码

  • protected void finalize() throws Throwable

等待当前线程,直到另一个线程调用notify()

  • public final void wait() throws InterruptedException

等待当前线程,直到另一个线程在指定时间内调用notify()

  • public final void wait(long timeout) throws InterruptedException

等待当前线程,直到另一个线程在指定时间内调用notify()

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

通知等待线程对象锁可用

  • public final void notify()

通知所有等待线程对象锁可用

  • 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

更新于: 2020年2月24日

4K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告