AppDividend
Latest Code Tutorials

Java Object Class Tutorial With Example | Java.lang.Object Class Tutorial

0

Java Object Class Tutorial With Example | Java.lang.Object Class Tutorial is today’s topic. The Object class in Java can be thought of as the father of all other classes in Java. This is because every class defined in Java extends directly or indirectly from the Object class. This also means that the methods of the Object class are available to all other classes in Java. Here’s how the Object class is defined in the java.lang package. See the following figure.

 

Java Object Class Tutorial

/*
Note: Following is the in-built Object class defined in java.lang
package. This class is shown here just for reference.

This piece of code will not compile by itself.
*/

/*
The Object class can be seen in the terminal by using the following
command.
~$ javap java.lang.Object

*/

/*
Compiled from "Object.java"
*/

public class java.lang.Object {

  public java.lang.Object();
  public final native java.lang.Class<?> getClass();
  public native int hashCode();
  public boolean equals(java.lang.Object);
  protected native java.lang.Object clone() throws java.lang.CloneNotSupportedException;
  public java.lang.String toString();
  public final native void notify();
  public final native void notifyAll();
  public final native void wait(long) throws java.lang.InterruptedException;
  public final void wait(long, int) throws java.lang.InterruptedException;
  public final void wait() throws java.lang.InterruptedException;
  protected void finalize() throws java.lang.Throwable;
  static {};
  
}

The above piece of code is not meant for compilation.

Java Object Class Tutorial

The java.lang.Object class is the root of a class hierarchy. Every class has Object as the superclass. All objects, including arrays, implement the methods of the Object class.

#Class Declaration

Following is the declaration for java.lang.Object class.

public class Object

#Class constructors

Sr.No. Constructor & Description
1 Object()

This is the Single Constructor.

#Methods of Object Class

Following are the methods defined in the Object class.

#getClass() in Java

Returns the class object of the object which invokes it.

public final Class<?> getClass()

See the following code example.

class ObjectEx1{ 
 
    public static void main(String [] args){

        Object ob = new Double(3.14); 
        Class c = ob.getClass(); 
        
        System.out.println("Class: " + c.getName()); 
    } 
}

See the following output.

 

getClass() in Java

#hashCode() in Java

Returns the hash value that is used to search an object in a collection. HashSet, HashMap, and Hashtable all use hashCode() method to save their respective objects. When an object is stored using a hash code, following the concept of hashing, it optimizes search in case of a large number of objects.

When we override the hashCode() method, it must be done in such a way that every instance of the class overriding the hashCode() method generates a unique number like a US Citizen’s Social Security number. See the following syntax.

public int hashCode()

See the following code example.

class Citizen{ 
    static int social_security_end = 85641221;  
    int social_security; 
  
    
    Citizen(){

        social_security = social_security_end; 
        social_security_end++; 
    } 
  
     
    public int hashCode(){ 
        return social_security; 
    } 
  
         
}

class ObjectEx2{
    public static void main(String [] args){ 
    
        Citizen x = new Citizen(); 
  
        System.out.println(x); 
        
    }
}

See output.

 

hashCode() in Java

#toString in Java

Converts an object to its String representation. When we print any object reference, it gives a call to the toString() method. See the syntax.

public String toString()

The default toString() method of the Object class is defined as follows:

public String toString(){
	return getClass().getName + “@” + Integer.toHexString(hashCode());
}

The default toString() method hence, returns the name of the class of the object and the unsigned hexadecimal representation of the object’s hashcode separated by the “@” symbol.

For general use with user-defined classes, the toString() method is overridden as demonstrated in the following program.

class A {

	public String toString(){
		return "Ah-Oh!";
	}
}

class ObjectEx3 {
	public static void main(String [] args){
		A obj = new A();
		System.out.println("Class A: " + obj);
	}
}

See the following output.

 

toString in Java

#equals(Object ob) in Java

This is a generic way to check objects for equality. Checks whether the object passed as argument is equal to the object invoking this method. See the following syntax.

public boolean equals(Object ob)

The equals() method can be overridden to check equality for user-defined classes as demonstrated in the program below.

class A{
	
}
class B{

}

class ObjectEx4{
	public static void main(String [] args){
		A a = new A();
		B b = new B();

		
		System.out.println("a equals b?: " + b.equals(a));
		System.out.println("a equals a?: " + a.equals(a));


	}
}

See the following output.

 

equals(Object ob) in Java

It is necessary to override the hashCode() method if equality is to be maintained because equal objects must have equal hash codes.

#finalize() in Java

The finalize() method is called by the Garbage Collector when there are no more references to the object in question. Thus, finalize() is called just before an object is a garbage collected. Even though garbage collection can be done multiple times on an object, the finalize() method is called only once.

See the following syntax of the finalize() method.

protected void finalize()

See the following program.

class ObjectEx5{
	public static void main(String [] args){
		ObjectEx5 ob = new ObjectEx5();
		ob = null;
		System.gc();
	}

	protected void finalize(){
		System.out.println("Finalized.");
	}
}

See the following output.

 

finalize() in Java

#clone() in Java

It returns a new object that is an exact clone, i.e., the same as the object which calls it. This method throws the CloneNotSupportedException if it is not possible to make a clone for the object in question. For example, in case of a Thread object, when the clone() method is called, it always throws the CloneNotSupportedException as it is not possible to meaningfully clone a thread.

See the following syntax.

protected Object clone() throws CloneNotSupportedException

See the following program.

class A implements Cloneable{

	int x, y;
	public Object clone() throws CloneNotSupportedException{ 
        return super.clone(); 
    }

    public void showValue(){
    	System.out.println(x);
    	System.out.println(y);
    } 
}

class ObjectEx6{
	
	public static void main(String [] args) throws CloneNotSupportedException{
	A a = new A();
	a.x=100;
	a.y=111;

	a.showValue();

	A b = (A)a.clone();

	b.showValue();

			
	}
}

See the output.

 

clone() in Java

#wait() in Java

The wait() method causes a current thread to wait until another thread invokes the notify() or the notifyAll() method for the object in question.

See the following syntax.

public final void wait() throws InterruptedException

See the following program.

import java.util.*;

class A{
	
	List l;

	A(){
		l = Collections.synchronizedList(new LinkedList());
	}

	public String remove() throws InterruptedException{
		synchronized(l){
			while(l.isEmpty()){
				System.out.println("Empty List.");
				System.out.println("Waiting...");
				l.wait();
				
			}
			String str = (String)l.remove(0);
			return str;
		}
		
	}

}

class ObjectEx7{
	public static void main(String [] args) throws InterruptedException{
		A a = new A();
		a.remove();

	}
}

//This program will not terminate.

See the following output.

wait() in Java

 

The above program will not terminate by itself. This is because the wait() method being called is being run indefinitely.

notify()

The notify() method releases the wait on the waiting thread on the invoking object’s monitor so that it can continue execution. The syntax is following.

public final void notify()

notifyAll()

The notifyAll() method releases the wait on all the waiting threads on the invoking object’s monitor so that they can continue execution. The Syntax is following.

public final void notifyAll()

Note

The notify() can be used to wake up only one thread which is waiting for a particular object whereas notifyAll() can be used to wake up all the threads of a specific object.

Finally, Java Object Class Tutorial With Example Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.