Java.lang.Object class is the root or superclass of the class hierarchy, which is present in java.lang package. All predefined classes and user-defined classes are the subclasses from Object class.
Why object class is a superclass
Re-usability
- Every object has 11 common properties, these properties must be implemented by every Java developer.
- To reduce the burden on the developer SUN developed a class called Object by implementing all these 11 properties with 11 methods.
- All these methods have generic logic common for all the subclasses, if this logic is not satisfying subclass requirement then subclass can override it
Runtime polymorphism
- To achieve runtime polymorphism so that we can write a single method to receive and send any type of class object as an argument and as return type.
Common functionalities of every class object
Comparing two objects
- public boolean equals(Object obj)
Retrieving hashcode
- public int hashcode()
Retrieving the run time class object reference
- public final Class getClass()
Retrieving object information in String format
- public String toString()
Cloning object
- protected Object clone() throws CloneNotSupportedException
Object clean-up code/ resources releasing code
- protected void finalize() throws Throwable
To wait for current thread until another thread invokes the notify()
- public final void wait() throws InterruptedException
To wait for current thread until another thread invokes the notify() a specified amount of time
- public final void wait(long timeout) throws InterruptedException
To wait for current thread until another thread invokes the notify() a specified amount of time
- public final void wait(long timeout, int nano) throws InterruptedException
Notify about object lock availability to waiting thread
- public final void notify()
Notify about object lock availability to waiting threads
- public final void notifyAll()
Example
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 } }
Output
This is: Adithya