Object and Object Class in Java

What is an Object in Java ?

We all know that Java is an Object Oriented Programming Language, which entirely rely on Objects and Classes. Any entity which has State and Behavior is known as Object, for example note, pen, bike, book etc. It can be either physical or logical. All the objects should have the below two characteristics

  1. State : State represents the bof the objects, Lets take car as example car has name, color, engine etc.
  2. Behavior : Behavior represents the functionality of that object. With car you can drive, apply breaking, change gear etc.

How to create object in java

Class is a blueprint for Object, you can create a object from a class. Lets take Demo class and try to create Java object for it.

public class Demo 
{
    String value = null;
    public Demo(String value)
    {
        this.value = value;
    }
    public void disp()
    {
        System.out.println("Welcome "+value+"!!!");
    }
    public static void main(String args[])
    {
        Demo d = new Demo("JavaInterviewPoint");
        d.disp();
    }
}
  1. Declaration: “Demo d”, this associates the variable name with an object type.( Here it is Demo type )
  2. Instantiation: The new Keyword is the one which creates the Object here
  3. Initialization: The new keyword is followed by a call to a constructor, which initializes the new object.

Different Ways to Create an Object in Java ?

There are around 5 different ways to create object in Java.

1. Using new keyword

This is the most popular way of creating a object in java which we have discussed above, almost every Java Developer knows this methodology

public class Sample1 
{
    String value = null;
    public Sample1(String value)
    {
        this.value = value;
    }
    public void display()
    {
        System.out.println("Welcome "+value+"!!!");
    }
    public static void main(String args[])
    {
        Sample1 s1 = new Sample1("JavaInterviewPoint");
        s1.display();
    }
}

2. Using class.forName()

Class.forName() will load the class dynamically and it indirectly will give you  “Class class” object. Once the class is loaded we will be using newInstance() method to create the object dynamically. Lets create a Java object for the Test class here

public class Test 
{
    static
    {
        System.out.println("Static block called");
    }
    public Test()
    {
        System.out.println("Inside Test class constructor");
    }

}
public class Logic 
{
    public static void main(String args[]) 
    {
        try {
            String className = "Test";
            Class clasz = Class.forName(className);
            Object obj = clasz.newInstance();
        }
        catch (ClassNotFoundException e) 
        {
            e.printStackTrace();
        } catch (InstantiationException e) 
        {
            e.printStackTrace();
        } catch (IllegalAccessException e) 
        {
            e.printStackTrace();
        }
    }
}

The below line creates the object of type Class encapsulating the class (Test) which we have provide

Class clasz = Class.forName(className);

The class Class has a method newInstance() which will create object for our Test class

Object obj = clasz.newInstance();

3. Using Class Loader and newInstance() Method

This is almost similar to that of the above one (class.forName) which load a class dynamically, here we will be using Class Loader to load the class dynamically

package com.javainterviewpoint;

public class Test 
{
    public void disp()
    {
        System.out.println("Disp Method Called");
    }
    public static void main(String args[])
    {
        try {
            ClassLoader cl = Test.class.getClassLoader();
            Test t = (Test)cl.loadClass("com.javainterviewpoint.Test").newInstance();
            t.disp();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

The below line get the ClassLoader type of object of Test class.

ClassLoader cl = Test.class.getClassLoader();

The ClassLoader class has a method loadClass() which loads the class and on top of it we will call the newInstance() method which creates and return the object of Object type, hence it is typecasted to Test type

Test t = (Test)cl.loadClass("com.javainterviewpoint.Test").newInstance();

4. Using Object Deserialization

In this approach we will be using Serializable interface in java which is a marker interface(method with no body) for serializing a Java Object s1 into a text file (persist.txt) and using object deserialization we will be reading and assigning it to a new object s2

import java.io.Serializable;

public class Sample implements Serializable
{
    String name;
    
    public Sample(String name) 
    {
        this.name = name;
    }
    public void show()
    {
        System.out.println("Hello "+name+"!!");
    }
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Serialization_Example 
{
    public static void main(String args[])
    {
        //Path to store the Serialized object
        String filePath="c://Persist.txt";
        Sample s1 = new Sample("JavaInterviewpoint");
        try
        {
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
            outputStream.writeObject(s1);
            outputStream.flush();
            outputStream.close();
            
            FileInputStream fileInputStream = new FileInputStream(filePath);
            ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
            Sample s2 = (Sample) inputStream.readObject();
            
            inputStream.close();
            
            s2.show(); 
        }
        catch(Exception ee)
        {
            ee.printStackTrace();
        }
    }
}

5. Using Object Cloning – clone() method

The clone() method is used to create a copy of an existing object, in order to use clone() method the corresponding class should have implemented Cloneable interface which is again a Marker Interface. In this approach we will be creating an object for Sample class “sample1” and using clone() method we will be cloning it to “sample2” object

public class Sample implements Cloneable
{
    String name;
    
    public Sample(String name) 
    {
        this.name = name;
    }
    public void show()
    {
        System.out.println("Hello "+name+"!!");
    }
    public static void main(String args[])
    {
        Sample sample1 = new Sample("World");
        try 
        {
            Sample sample2 = (Sample)sample1.clone();
            sample2.show();
        } catch (CloneNotSupportedException e) 
        {
            e.printStackTrace();
        }        
    }
}

Object class in Java

The Object class is the Parent class of all the classes in Java. In other words java.lang.Object class is the root of the Class Hierarchy. For each and every class which we create this class will be acting as the Super class and that is the reason why we are able to use hashCode(), toString(), wait() etc.. methods directly which actually belongs to the Object class

All the class which is declared will be extending the class Object, even though if we didn’t specify it directly it will be happening implicitly. This will be taken care by the JVM itself, but it doesn’t apply to Interfaces, as a Java Interface cannot extend a class.

Methods of Java Object class

Lets look into the methods in class Object

METHODS DESCRIPTION
public int hashCode() This method returns the hashcode of the java object.
public boolean equals(Object obj) Compares the given object to this object.
protected Object clone() throws CloneNotSupportedException This method creates and returns the exact copy (clone) of this object.
public String toString() Returns the string representation of this object.
public final Class getClass() Returns the Class class object of the object.
public final void notify() This method wakes up a single thread that is waiting on this object’s monitor.
public final void notifyAll() This method wakes up all threads that are waiting on this object’s monitor.
public final void wait(long timeout)throws InterruptedException This method makes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int nanos)throws InterruptedException This method makes the current thread to wait for the specified miliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait()throws InterruptedException This method makes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable This method is invoked by the garbage collector before object is being garbage collected.

Is Object Class the Super Class of all Java Classes?

Lets run a simple test to prove that Object class is the super class of all classes in java. We will use getSuperClass() method of Class class and see what happens.

public class Test 
{
	public static void main(String args[])
	{
	    /**
	     * Create objects for three classes
	    1. Class - Test
	    2. Class - String
	    3. Class - Object
	    **/
	    Test test = new Test();
	    String str = new String("Hello");
	    Object obj = new Object();
	    
	    //Get the superClass of each objects
	    System.out.println("Super class of Test class is : "+test.getClass().getSuperclass());
	    System.out.println("Super class of String class is : "+str.getClass().getSuperclass());
	    System.out.println("Super class of Object class is : "+obj.getClass().getSuperclass());
	}
}

Output 

Super class of Test class is : class java.lang.Object
Super class of String class is : class java.lang.Object
Super class of Object class is : null

In the above code we can see that for our Test and String (java.lang.String) class the super class is getting displayed as “java.lang.Object” but for Object class alone it is displayed as null. This is a simple proof which tells us Object class is the super class for all the classes.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s