Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

What Are the Different Ways to Create an Object in Java?

DZone's Guide to

What Are the Different Ways to Create an Object in Java?

There are a lot of different ways you can create an object in Java.

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

In this quick article, we will discuss five different ways to create an object in Java. As we know, a class is a template or blueprint from which objects are created. Let's list out the 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 the Class class

3. Using newInstance() method of the Constructor class

4. Using Object Deserialization

5. Using Object Cloning – clone() method

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 the Student object using the 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 the “Class class” object. Once the class is loaded, we will be using thenewInstance()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);


ThenewInstance() 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 onenewInstance() 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 the Student class object using the  newInstance() method of  java.lang.reflect.Constructorclass:

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 implement 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 the Student class “student1” and, using the 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


Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
java ,tutorial ,object ,string ,constructor class ,class ,cloning ,deserialization

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}