View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Object Creation in Java: Explained with Examples

Updated on 24/04/20254,703 Views

In Java, object creation is one of the most fundamental concepts that powers the language's object-oriented nature. Every time you create an instance of a class, you're creating an object. Understanding how objects are created helps you write efficient, maintainable, and dynamic code.

In this blog, we will explore all the ways of object creation in Java programming, break down what happens behind the scenes, and provide code examples to make it easy for beginners and intermediate learners.

Want to master Java and build real-world applications? Explore upGrad's Software Engineering course and level up your coding career.

What is an Object in Java?

An object is a class instance that contains state (fields/variables) and behavior (methods). While a class is just a blueprint, an object is a real entity created in memory using that blueprint.

For example:

class Car {
    String color = "Red";
    void drive() {
        System.out.println("Car is driving...");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car(); // 'myCar' is an object
        myCar.drive();
    }
}

Output:

Car is driving...

Explanation:

In the example, myCar is an object of the Car class created using the new keyword. It has access to the class members, so calling myCar.drive() prints "Car is driving..." to the console.

Looking to combine your Java skills with data science? Enroll in the Executive Diploma in Data Science & AI by IIIT-B and upGrad to future-proof your career.

Steps Involved in Object Creation in Java

When creating an object using the new keyword, Java follows three essential steps:

1. Declaration

This step creates a reference variable that can point to an object of a specific class type.

Car myCar;

Here, myCar is declared as a reference variable of type Car. At this point, it doesn’t point to any object in memory—just the name and type are known to the compiler.

2. Instantiation

This step uses the new keyword to create a new object in heap memory.

new Car();

Explanation:

The new keyword allocates memory for a new Car object. However, this object isn’t yet connected to a variable, so it’s not usable unless assigned to a reference.

3. Initialization

This step calls the class constructor to initialize the object’s fields.

Car();

 Explanation:

This is a call to the class constructor, which sets up the object with its initial state. It is executed automatically when new Car() is used.

Putting it all together

class Car {
    String color = "Red";
    void drive() {
        System.out.println("Car is driving...");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();  // Declaration + Instantiation + Initialization
        myCar.drive();
    }
}

Final Explanation:

  • Car myCar; → Declaration: You declare a reference.
  • new Car(); → Instantiation: Memory is allocated.
  • Car() → Initialization: Constructor is called.

All three steps are commonly combined in a single line:

Car myCar = new Car();

This sequence is the foundation of object-oriented programming in Java.

Want to integrate your Java skills with cloud and DevOps? Explore the Professional Certificate Program in Cloud Computing and DevOps to boost your backend and deployment expertise.

Different Ways to Create Objects in Java

Java offers multiple approaches for creating objects, each suited to different scenarios and use cases. Understanding the various ways of object creation in Java is essential for writing flexible and efficient code, especially in advanced applications like frameworks or serialization.

1. Using new Keyword

This is the most direct and widely used way to create objects in Java. It involves using the new keyword, which handles instantiation and calls the constructor to initialize the object.

class Car {
    void drive() {
        System.out.println("Car is driving...");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car1 = new Car();
        car1.drive();
    }
}

Output:

Car is driving...

Explanation:

Here, car1 is created by combining declaration, instantiation, and initialization in a single line. The new keyword creates the object in memory, and the constructor sets it up for use.

2. Using clone() Method

This method creates a copy of an existing object in memory. The class must implement the Cloneable interface and override the clone() method. It’s useful when you need object duplication.

class Car implements Cloneable {
    String color = "Blue";

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

public class Main {
    public static void main(String[] args) throws Exception {
        Car car1 = new Car();
        Car car2 = (Car) car1.clone();
        System.out.println(car2.color);
    }
}

Output: 

Blue

Explanation:

car2 is a cloned copy of car1. Both are separate objects in memory but have the same data. Without implementing Cloneable, this will throw CloneNotSupportedException.

3. Using Deserialization

Deserialization creates an object by reading its state from a file or byte stream. The class must implement Serializable and the object should be serialized before deserialization.

import java.io.*;

class Car implements Serializable {
    String model = "Sedan";
}

public class Main {
    public static void main(String[] args) throws Exception {
        // Serialize
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("car.ser"));
        Car car1 = new Car();
        out.writeObject(car1);
        out.close();

        // Deserialize
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("car.ser"));
        Car car2 = (Car) in.readObject();
        in.close();

        System.out.println(car2.model);
    }
}

Output:

Sedan

Explanation:

The object car1 is written to a file and then restored using deserialization. This technique is useful in saving and retrieving object states across sessions or systems.

4. Using Class.forName().newInstance() (Deprecated since Java 9)

This method dynamically loads the class by its name and creates an instance. It's part of the Reflection API but deprecated due to better alternatives. Suitable for frameworks or plugins.

class Car {
    void start() {
        System.out.println("Car started");
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        Class<?> cls = Class.forName("Car");
        Car car = (Car) cls.newInstance();
        car.start();
    }
}

Output:

Car started

Explanation:

This approach uses the fully qualified class name to create an object at runtime. However, newInstance() is deprecated and replaced by safer, more flexible alternatives like Constructor.newInstance().

5. Using Constructor.newInstance() (Reflection)

This is a more flexible and preferred method in Reflection. It allows invoking any constructor (even parameterized ones) and provides better exception handling than Class.newInstance().

import java.lang.reflect.Constructor;

class Car {
    public Car() {
        System.out.println("Car object created using Constructor.newInstance()");
    }

    void display() {
        System.out.println("Display method called");
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        Constructor<Car> constructor = Car.class.getConstructor(); // No-arg constructor
        Car car = constructor.newInstance(); // Create object using reflection
        car.display();
    }
}

Output:

Car object created using Constructor.newInstance()

Display method called

Explanation:

This method uses Java Reflection to access the no-argument constructor of the Car class. The constructor must be explicitly declared as public. This method is flexible and widely used in frameworks for runtime object creation.

Comparison of Java Object Creation Methods

Method

Simplicity

Use Case

Reflection Needed

Common Usage

new Keyword

High

General-purpose programming

No

Very common

clone()

Medium

Duplicating existing objects

No

Limited

Deserialization

Low

Restoring from file/stream

No

Niche (e.g., I/O)

Class.forName().newInstance()

Medium

Dynamic class loading

Yes

Deprecated

Constructor.newInstance()

Medium

Frameworks, tools

Yes

Common in frameworks

Best Practices for Object Creation

  • Prefer constructors with the new keyword for clarity and simplicity.
  • Avoid reflection unless you need dynamic object creation (e.g., frameworks).
  • Use deserialization cautiously due to potential security issues.
  • Ensure Cloneable is properly implemented if using clone().

Conclusion

Java offers various ways to create objects, each with its own use case. While the new keyword is the most straightforward and commonly used method, others like cloning, deserialization, and reflection are useful in specialized scenarios. Understanding these methods can help you write more dynamic and flexible Java code.

FAQs

1. What is object creation in Java?

Object creation in Java is the process of instantiating a class to form a usable object in memory. It involves declaring a reference, allocating memory using the new keyword, and initializing it through a constructor, allowing access to class properties and methods.

2. What are the different ways to create objects in Java?

Java provides five main ways to create objects: using the new keyword, clone() method, deserialization, Class.forName().newInstance() (deprecated), and Constructor.newInstance() via Reflection. Each method serves specific use cases, ranging from basic instantiation to advanced dynamic object creation.

3. What are the steps involved in object creation in Java?

Object creation in Java typically involves three steps: Declaration (declaring a reference variable), Instantiation (allocating memory with new), and Initialization (calling the constructor to set initial values). These steps together create a usable object instance in memory.

4. What is the most commonly used way to create an object in Java?

The most commonly used and recommended method is using the new keyword. It clearly shows intent, directly calls the class constructor, and is widely supported, making it suitable for most object creation scenarios in Java applications.

5. Can you create an object without using the new keyword?

Yes, Java allows object creation without the new keyword using methods like clone(), deserialization, and reflection-based approaches such as Class.forName() and Constructor.newInstance(). These are often used in advanced scenarios like frameworks and object restoration.

6. What is cloning in Java and how does it work?

Cloning creates a copy of an existing object in memory. It requires the class to implement the Cloneable interface and override the clone() method. This is useful for duplicating objects without creating new instances from scratch.

7. Why is Class.newInstance() deprecated?

Class.newInstance() is deprecated because it lacks proper exception handling, supports only no-argument constructors, and provides limited flexibility. It has been replaced by Constructor.newInstance() which offers more robust object creation through reflection and better exception management.

8. What is the use of Constructor.newInstance() in Java?

Constructor.newInstance() allows creating objects at runtime using reflection. It supports both default and parameterized constructors, making it a powerful tool for dynamic object creation in frameworks, tools, or dependency injection mechanisms.

9. How does deserialization create an object in Java?

Deserialization recreates an object from a byte stream, typically read from a file or network. It restores the object’s state exactly as it was during serialization, without calling constructors. It’s useful for saving and retrieving object data.

10. What are the risks of using deserialization for object creation?

Deserialization can pose serious security risks, especially if the byte stream comes from an untrusted source. It can lead to unauthorized object manipulation or remote code execution if not properly validated and secured in enterprise applications.

11. Which object creation method should I use?

Use the new keyword for most scenarios as it’s safe and simple. Choose cloning for duplicating existing objects, deserialization for restoring object state, and reflection-based methods when dynamic instantiation is necessary, such as in frameworks or libraries.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.