5 Different Ways to Create an Objects in Java


In this quick article, we will discuss 5 different ways to create an Object in Java. As we know that, a class is a template or blueprint from which objects are created. Let's list out different ways to create objects in Java.

5 Different Ways to Create Objects in Java

1. Using a new keyword
2. Using newInstance() method of Class class
3. Using newInstance() method of Constructor class 
4. Using Object Deserialization
5. Using Object Cloning – clone() method

1. Using a new keyword

This is the most popular way of creating an object in java which we have discussed above, almost every Java Developer knows this methodology.
package net.javaguides.corejava.oops;

public class Student {
    private String name;
    private String college;

    public Student(String name, String college) {
        super();
        this.name = name;
        this.college = college;
    }

    public String getName() {
        return name;
    }

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

    public void setCollege(String college) {
        this.college = college;
    }

    public static void main(String[] args) {

        Student student = new Student("Ramesh", "BVB");
        Student student2 = new Student("Prakash", "GEC");
        Student student3 = new Student("Pramod", "IIT");
    }
}
From the above code, we are creating Student object using new keyword:
Student student = new Student("Ramesh", "BVB");
Student student2 = new Student("Prakash", "GEC");
Student student3 = new Student("Pramod", "IIT");

2. Using newInstance() method of Class class

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.
Let's create a Java object for the Student class here:
package net.javaguides.corejava.oops;

public class Student {
    private String name = "Ramesh";
    private String college = "ABC";

    public Student() {
        super();
    }

    public Student(String name, String college) {
        super();
        this.name = name;
        this.college = college;
    }

    public String getName() {
        return name;
    }

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

    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }

    public static void main(String[] args) {
        try {

            String className = "net.javaguides.corejava.oops.Student";
            Class clasz = Class.forName(className);
            Student student = (Student) clasz.newInstance();
            System.out.println(student.getName());
            System.out.println(student.getCollege());

        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Output:
Ramesh
ABC
The forName() method returns the Class object associated with the class or interface with the given string name.
Class clasz = Class.forName(className);
newInstance() method creates a new instance of the class represented by this Class object.
Student student = (Student) clasz.newInstance();
System.out.println(student);

3. Using newInstance() method of Constructor class 

Similar to the newInstance() method of Class class, There is one newInstance() method in the java.lang.reflect.Constructor class which we can use to create objects. We can also call a parameterized constructor, and private constructor by using this newInstance() method.
Let's demonstrate this approach by creating Student class object using newInstance() method of java.lang.reflect.Constructor class:
package net.javaguides.corejava.oops;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Student {
    private String name = "Ramesh";
    private String college = "ABC";

    public Student() {
        super();
    }

    public Student(String name, String college) {
        super();
        this.name = name;
        this.college = college;
    }

    public String getName() {
        return name;
    }

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

    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }

    public static void main(String args[]) {
        Constructor < Student > constructor;
        try {
            constructor = Student.class.getConstructor();
            Student student = constructor.newInstance();
            System.out.println(student.getName());
            System.out.println(student.getCollege());
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException |
            NoSuchMethodException | SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
Output:
Ramesh
ABC

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 Student Object s1 into a text file (sample.txt) and using object deserialization we will be reading and assigning it to a new Student object s2.
package net.javaguides.corejava.oops;

import java.io.Serializable;

public class Student implements Serializable{
 private String name;
 private String college;

 public Student() {
  super();
 }

 public Student(String name, String college) {
  super();
  this.name = name;
  this.college = college;
 }

 public String getName() {
  return name;
 }

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

 public String getCollege() {
  return college;
 }

 public void setCollege(String college) {
  this.college = college;
 }
}
package net.javaguides.corejava.oops;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class StudentDemo {
    public static void main(String[] args) {
        // Path to store the Serialized object
        String filePath = "sample.txt";
        Student s1 = new Student("Ramesh", "ABC");
        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);
            Student s2 = (Student) inputStream.readObject();

            inputStream.close();

            System.out.println(s2.getName());
            System.out.println(s2.getCollege());
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }
}
Output:
Ramesh
ABC

5. Using Object Cloning – clone() method

The clone() method is used to create a copy of an existing object, in order to the clone() method the corresponding class should have implemented a Cloneable interface which is again a Marker Interface. 
In this approach we will be creating an object for Student class “student1” and using clone() method we will be cloning it to “student2” object
package net.javaguides.corejava.oops;

import java.io.Serializable;

public class Student implements Cloneable {
    private String name;
    private String college;

    public Student() {
        super();
    }

    public Student(String name, String college) {
        super();
        this.name = name;
        this.college = college;
    }

    public String getName() {
        return name;
    }

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

    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }

    public static void main(String args[]) {
        Student student1 = new Student("Ramesh", "ABC");
        try {
            Student student2 = (Student) student1.clone();
            System.out.println(student2.getName());
            System.out.println(student2.getCollege());
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}
Output:
Ramesh
ABC

Related Articles

Comments

  1. Very useful article, especially beginners should know all these techniques

    ReplyDelete

Post a Comment