Object class in Java and its methods
Object is the Parent class for all class in java api and user defined classes. Object is called as "Root" class for class hierarchy.
This is available when Java invented and from version 1.0. Object class is in package of "java.lang.Object"
If we are not aware user what type of data sending, Object can accept all types of data.
This is available when Java invented and from version 1.0. Object class is in package of "java.lang.Object"
If we are not aware user what type of data sending, Object can accept all types of data.
Example:
public void method(Object obj){
// Some operations
}
Object class Constructor:
public Object()
Constructor will be used to instantiate Object class.
Object class has following methods.
1) protected Object clone() throws CloneNotSupportedException
Which returns some copy of Object. Cloned class should implements Clonable interface.
Eg. obj.clone();
2) public boolean equals(Object obj)
Equals() method compares references of two objects. If both are referring to same object than returns true, else false. This does not compare data.
Eg. obj1.equals(obj2);
3) protected void finalize() throws Throwable
finalize method is invoked by Garbage Collector when the object is not referenced or not being in use by any thread. finalize should be overridden by subclass.
Eg. protected void finalize() throws Throwable{
System.out.println("Garbage Collector has invoked finalize method");
}
4) public final Class<?> getClass()
Which returns runtime object class including package.
Eg. System.out.println("policies.getClass() :: "+ policies.getClass());
Output:
policies.getClass() :: class [Ljava.lang.String;
5) public int hashCode()
Which returns unique code for each object. This is used in implementation of Hashtable.
6) public final void notify()
Wakes up a single thread that is waiting on this object's monitor
7) public final void notifyAll()
Wakes up all threads that are waiting on this object's monitor
8) public String toString()
toString method returns String representation of Object. Below snippet is from toString method java api.
getClass().getName() + '@' + Integer.toHexString(hashCode())
class name + @ + hashCode in hexa decimal format.
Eg. System.out.println("employee1.toString() :: " + employee1.toString());
Output:
employee1.toString() :: com.java.w3schools.core.inheritance.Employee@f93ee4
9) public final void wait() throws InterruptedException
To make current thread to wait until another thread completes their task and invoke notify method.
10) public final void wait(long timeout) throws InterruptedException, public final void wait(long timeout, int nanos) throws InterruptedException
to make thread wait until notify or notifyAll method is invoked or after elapsing specified time.
No comments:
Post a Comment
Please do not add any spam links in the comments section.