How to Create an Object

JavaJavaBeginner
Practice Now

Introduction

In Java, creating an object is a fundamental concept of Object-Oriented Programming (OOP) that enables us to use a class's blueprint. An object represents real-life entities and has properties like real-life entities. In this lab, we will learn how to create an object of a class.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/ConcurrentandNetworkProgrammingGroup(["`Concurrent and Network Programming`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/annotation("`Annotation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inner_classes("`Inner Classes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/serialization("`Serialization`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_attributes("`Class Attributes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/encapsulation("`Encapsulation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/ConcurrentandNetworkProgrammingGroup -.-> java/threads("`Threads`") java/FileandIOManagementGroup -.-> java/files("`Files`") java/FileandIOManagementGroup -.-> java/create_write_files("`Create/Write Files`") java/FileandIOManagementGroup -.-> java/read_files("`Read Files`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/StringManipulationGroup -.-> java/strings("`Strings`") subgraph Lab Skills java/scope -.-> lab-117433{{"`How to Create an Object`"}} java/annotation -.-> lab-117433{{"`How to Create an Object`"}} java/inner_classes -.-> lab-117433{{"`How to Create an Object`"}} java/serialization -.-> lab-117433{{"`How to Create an Object`"}} java/classes_objects -.-> lab-117433{{"`How to Create an Object`"}} java/class_attributes -.-> lab-117433{{"`How to Create an Object`"}} java/class_methods -.-> lab-117433{{"`How to Create an Object`"}} java/encapsulation -.-> lab-117433{{"`How to Create an Object`"}} java/modifiers -.-> lab-117433{{"`How to Create an Object`"}} java/oop -.-> lab-117433{{"`How to Create an Object`"}} java/packages_api -.-> lab-117433{{"`How to Create an Object`"}} java/threads -.-> lab-117433{{"`How to Create an Object`"}} java/files -.-> lab-117433{{"`How to Create an Object`"}} java/create_write_files -.-> lab-117433{{"`How to Create an Object`"}} java/read_files -.-> lab-117433{{"`How to Create an Object`"}} java/identifier -.-> lab-117433{{"`How to Create an Object`"}} java/arrays -.-> lab-117433{{"`How to Create an Object`"}} java/comments -.-> lab-117433{{"`How to Create an Object`"}} java/data_types -.-> lab-117433{{"`How to Create an Object`"}} java/operators -.-> lab-117433{{"`How to Create an Object`"}} java/strings -.-> lab-117433{{"`How to Create an Object`"}} end

Create a Class

The first step is to create a class that represents an entity with properties. For example, let's create a class called Car that represents a car's real-life entity with properties like color, brand name, and fuel type.

public class Car {
    private String carColor;
    private String brand;
    private String fuelType;

    public void start() {
        //code to start the car
    }

    public void stop() {
        //code to stop the car
    }
}

Create an Object Using new Keyword

To create an object in Java, use the new keyword with a constructor. In the following example, we create an object called myCar using the new keyword. We call the start() and stop() methods using the myCar object.

public class Main {
    public static void main(String[] args) {
        //Creating an object using the new keyword
        Car myCar = new Car();

        //Calling methods using the object
        myCar.start();
        myCar.stop();
    }
}
Running the Code

To run the code, execute the following command in the terminal:

javac Main.java && java Main

Create an Object Using newInstance() Method

An object can also be created using the newInstance() method of the Class class. In the following example, we create an object of a Student class called newStudent using the newInstance() method.

class Student {
    private String name;
    private int id;
}

public class Main {
    public static void main(String[] args) throws Exception {
        //Creating an object using the newInstance() method
        Student newStudent = Student.class.newInstance();

        //Assigning values to the object
        newStudent.name = "John";
        newStudent.id = 123;
    }
}
Running the Code

To run the code, execute the following command in the terminal:

javac Main.java && java Main

Create an Object Using clone() Method

The clone() method can be used to create an object if at least one object of the class is already created. In the following example, we create an object of a Student class called newStudent using the clone() method.

class Student implements Cloneable {
    private String name;
    private int id;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        //Creating an object
        Student student = new Student();
        student.name = "John";
        student.id = 123;

        //Cloning the object
        Student newStudent = (Student) student.clone();
    }
}
Running the Code

To run the code, execute the following command in the terminal:

javac Main.java && java Main

Create an Object Using Serialization and Deserialization

Creating an object using serialization and deserialization is a way of creating an object that requires the class to be serializable. In the following example, we create an object of a Student class called newStudent using serialization and deserialization.

import java.io.Serializable;

class Student implements Serializable {
    private String name;
    private int id;
}

public class Main {
    public static void main(String[] args) throws Exception {
        //Creating an object
        Student student = new Student();
        student.name = "John";
        student.id = 123;

        //Serialization of the object
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.obj"));
        out.writeObject(student);
        out.close();

        //Deserialization of the object
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("file.obj"));
        Student newStudent = (Student) in.readObject();
        in.close();
    }
}
Running the Code

To run the code, execute the following command in the terminal:

javac Main.java && java Main

Summary

To create an object of a class in Java:

  1. Create a class with properties.
  2. Use the new keyword with a constructor to create an object.
  3. Create an object using the newInstance() method of the Class class.
  4. Create an object using the clone() method of an object if at least one object of the class is already created.
  5. Create an object using serialization and deserialization.

Other Java Tutorials you may like