Java object

Object is a fundamental entity of any java application and every developer creates objects while coding.
An object is an instance of a class and there are many different methods of object creation in java.
This post will demonstrate 5 various ways of the same with example.

Sample class

Below is the class which we will be using for creating objects by different methods shown later.

import java.io.Serializable;

/**
 * Student class
 *
 */
class Student implements Serializable, Cloneable {
   private String name;
	
   private int age;
	
   /**
    * No argument constructor
    *
    */
   public Student() {

   }

   /**
    * Overloaded constructor
    *
    */
   public Student(String name, int age) {
      this.name = name;
      this.age = age;
   }

   public String getName() {
	return name;
   }

   public void setName(String name) {
	this.name = name;
   }

   public int getAge() {
	return age;
   }

   public void setAge(int age) {
	this.age = age;
   }

   /**
    * clone method
    *
    */
   public Object clone() throws CloneNotSupportedException {
	return super.clone();
   }
}

Note that this class implements java.io.Serializable and java.lang.Cloneable interfaces.
It is not mandatory for a class to implement these and is required only when Methods 2 and 3 discussed below are used.

Method 1: Using new operator

This is the most commonly used method of creating an object and almost all programmers use it when creating an object. Syntax is

ClassName reference = new ClassName();

Example,

 

Student student = new Student();

where new is a keyword for creating an object.
Right side after the new operator will invoke the constructor of the class. Thus, the class should have a constructor matching the signature. Thus, if you write

Student student = new Student(“John”, 15);

then the Student class should have a constructor that accepts a String and an integer argument. Complete example is given below

public class NewOperatorDemo {
  public static void main(String... args) {
    // create an object
    Student student = new Student();
    // create another object
    Student otherStudent = new Student("John", 15);
    // prints false
    System.out.print(student.equals(otherStudent));    
  }
}

Method 2: Using clone method

clone() method is present in java.lang.Object class and is used for creating a copy of an object.
If clone is implemented properly, then the copy object will be a new object. Thus,

public class CloneMethodDemo {
  public static void main(String... args) {
    // create an object
    Student student = new Student();
    // create its copy
    Student newStudent = student.clone();
    // check if both point to the same memory location
    System.out.print(student.equals(newStudent)); // prints false
  }
}

References of both the objects when compared, it is confirmed that both the objects are different.

There are a couple of pre-requisites for creating an object using clone method. They are:

  1. The class whose clone needs to be created should implement java.lang.Cloneable interface.
  2. It should override clone method from java.lang.Object class.

Method 3: Using Serialization and deserialization

Serialization is a technique where you can save an object to a file and get an object back from the file using deserialization.
When deserializing, a new object is created but all the attribute values of the new object are the same as that of the serialized object.
Example,

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationDemo {
   public static void main(String... args) {
      // create an object using new
      Student student = new Student();
      // set its attributes
      ob.setAge(35);
      ob.setName("John");
      // serialize object to a file
      ObjectOutputStream out = new ObjectOutputStream(
               new FileOutputStream(new File("object.ser")));
      out.writeObject(ob);
      out.flush();
      out.close();
      // deserialize - read it back
      ObjectInputStream in = new ObjectInputStream(
               new FileInputStream(new File("object.ser")));
      Student newStudent = (Student)in.readObject();
      in.close();
      System.out.println(newStudent.equals(ob)); // prints false
   }
}

readObject() method will return a java.lang.Object and you need to explicitly cast it to required type.
When both the objects are compared, it is clear that both are different.
Remember that default equals method defined in java.lang.Object class compares the references of two objects and returns false if both the references point to different memory locations.

If you want to change the criteria for object comparison, then override equals in your class.

For this method to work, the class whose object is serialized and deserialized should implement java.io.Serializable interface.

Method 4: Using dynamic class loading

java.lang.Class has a newInstance method which creates a new object of the class referred by the instance of java.lang.Class object.
For creating an object of java.lang.Class, load the class dynamically using Class.forName method.
Example,

public class ClassDemo {
  public static void main(String... args) throws 
                  InstantiationException, 
                  IllegalAccessException, 
                  ClassNotFoundException {
    // load class   
    Class<?> studentClass = Class.forName("Student");
    // create object of student
    Student student = (Student)studentClass.newInstance();
  }
}

Note that forName() method is a static method of java.lang.Class.
It takes the name of the class to be loaded along with its package name as argument in String format.
Thus, the class to be loaded should be present on the class path of the program.
Remember that in this case, the constructor of the class is invoked.

newInstance() method has been deprecated since Java 9.
So, for using java.lang.Class instance to create a new object from Java 9 onwards, you need to get a constructor of the class first using its getDeclaredConstructors method and then call newInstance on it.
Example,

Class<?> studentClass = Class.forName("Student");
Constructors[] constructors = studenClass.getDeclaredConstructors();
// create object of student
Student student = (Student)constructors[0].newInstance(null);

getDeclaredConstructors() method returns an array of all the constructors declared in the class in the same order in which they are written.
Thus, when we try to get the first constructor, it will return the no-argument constructor. Calling newInstance() method on the constructor will return a new object.
newInstance() method takes an array of arguments that are expected by the constructor. Since our constructor does not expect any arguments, we supply null to it.
Above code can be replaced with a one-liner as below

Student student = (Student)Class.forName("Student")[0].newInstance(null);

Method 5: Using java.lang.Class

This is similar to above method but in this method you get an object of java.lang.Class using its class property instead of Class.forName method.
Rest all remains the same.
An advantage of this method is that if the class is not present, a compile time error will be generated preventing the program from breaking at execution time.
Example,

public class ObjectCreationDemo {
   public static void main(String... args) throws InstantiationException, 
                          IllegalAccessException{
      Class<?> studentClass = Student.class;
      Constructors[] constructors = studenClass.getDeclaredConstructors();
      // create object of student
      Student student = (Student)constructors[0].newInstance(null);
   }
}

Above code can also be replaced by a one-liner as below

Student student = (Student)Student.class.getDeclaredConstructors()[0].
                      newInstance(null);

In this method also, the constructor of class is called.

These are the different ways in which you can create an object of a class in java.
Hope the article was useful.

Leave a Reply