Course contentsShow
← Java
Lesson 313 of 2,8708. Classes and EncapsulationFree lesson

Creating Objects: Using new with Constructors

Understanding the process of instantiating objects using the new keyword and constructor calls.

Creating Objects: Using new with Constructors

What you'll learn: How to bring your class blueprints to life by instantiating actual objects using the new keyword and constructors.

The Instantiation Process

You've learned that a class is a blueprint and that constructors are special methods for initialization. Now it's time to actually create objects from those blueprints. This is called instantiation, and it happens when you combine the new keyword with a constructor call.

Think of it like ordering a custom car: the class is the car model design, the constructor is the order form where you specify options (color, engine, etc.), and new is the factory process that actually builds your specific car.

The Syntax

Here's how you create an object:

ClassName variableName = new ClassName(arguments);

Let's see this with a concrete example using a Dog class:

class Dog {
    String name;
    int age;
    
    // Constructor
    Dog(String n, int a) {
        name = n;
        age = a;
    }
}

// Creating objects
Dog buddy = new Dog("Buddy", 3);
Dog max = new Dog("Max", 5);

What Happens When You Use new

  1. Memory allocation: new allocates space on the heap for the new object
  2. Constructor execution: The constructor runs, initializing the object's fields
  3. Reference returned: new returns a reference to the newly created object
  4. Assignment: The reference is stored in your variable (buddy or max)

Each time you use new, you create a completely separate object with its own field values, even if you use the same constructor.

Key Takeaway: The new keyword combined with a constructor call is how you instantiate objects from a class blueprint—new allocates memory, the constructor initializes it, and you get back a reference to your new object.