DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. What Are the Different Ways to Create an Object in Java?

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.

Ramesh Fadatare user avatar by
Ramesh Fadatare
·
Nov. 21, 18 · Tutorial
Like (7)
Save
Tweet
Share
16.31K Views

Join the DZone community and get the full member experience.

Join For Free

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


Object (computer science) Java (programming language)

Published at DZone with permission of Ramesh Fadatare. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Stream Processing vs. Batch Processing: What to Know
  • Building a Scalable Search Architecture
  • Quick Pattern-Matching Queries in PostgreSQL and YugabyteDB
  • Agile Transformation With ChatGPT or McBoston?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: