Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Object Creation and Storage (Instantiation)

Lesson ~11 min read 8 MCQs

In simple terms: In simple terms, object creation is about using a class's "blueprint" (its constructor) to build a specific, usable object in your code, like ordering a custom item from a menu.

Why this matters

Imagine you're at a build-your-own-PC shop in Dallas. On the wall is a menu—the "Gamer-Pro" model. It lists all the possible components: CPU type, graphics card, RAM, storage size. That menu isn't a computer; it's a blueprint.

Now, you walk up to the counter and say, "I'll take a Gamer-Pro, but with the upgraded graphics card and 32GB of RAM." The technician takes your specific order, goes to the back, and assembles a real, physical computer just for you.

In Java, that blueprint is a class, and the specific computer you ordered is an object. The conversation you had at the counter—giving your specific requirements—is the constructor call. Today, we'll master how to place those orders in code to bring our objects to life.

Concept overview

flowchart TD
    A[Start in main method] --> B{Declare reference variable<br><code>Dog myDog;</code>};
    B --> C{Call constructor with `new`<br><code>... = new Dog("Fido", "Lab");</code>};
    C --> D[Program flow jumps to Dog constructor];
    subgraph Constructor Execution
        E[Initialize attributes<br><code>name = "Fido";</code><br><code>breed = "Lab";</code>]
    end
    D --> E;
    E --> F{Return memory address of new object};
    F --> G{Assign address to myDog variable<br><code>myDog</code> now points to the object};
    G --> H[Execution continues in main method];
    H --> I[End];
This diagram shows a flowchart of Java object creation. The process starts in the main method, moves to declaring a reference variable, then calls a constructor with the 'new' keyword. The flow then jumps to the constructor to initialize the object's attributes, returns a memory address, assigns it to the variable, and finally continues execution.

Core explanation

In programming, we define a class as a blueprint for creating things. A Dog class, for example, might define that all dogs have a name, a breed, and an age. But the class itself isn't a dog. It's just the idea of a dog. To get an actual dog in our program, we need to create an object. This process is called instantiation.

Think of it like this: the Dog class is the official American Kennel Club standard for a Golden Retriever. An object is your specific Golden Retriever, Maya, who is 3 years old and lives in your house.

So how do we do this? We use a special method called a constructor.

What is a Constructor?

A constructor is a block of code that runs when you create a new object. Its job is to set up the object's initial state.

Here are the two rules you must know:

  1. A constructor always has the exact same name as the class.
  2. A constructor never has a return type—not even void.

Let's look at a simple Dog class:

public class Dog {
    String name;
    String breed;
    int age;

    // This is the constructor!
    public Dog(String dogName, String dogBreed, int dogAge) {
        name = dogName;
        breed = dogBreed;
        age = dogAge;
    }
}

The part public Dog(...) is the constructor. Notice its name is Dog, just like the class. It takes in three pieces of information—a name, a breed, and an age—and uses them to initialize the object's instance variables.

The Dog class acts as a blueprint for individual Dog objects.

Declaring and Instantiating: The Two-Step Process

Creating an object is a two-step dance: declaration and instantiation.

Step 1: Declaration (Creating the Leash) First, you declare a variable that can hold a reference to a Dog object.

Dog myDog;

Think of this as buying a leash. You don't have a dog yet, but you have a place to attach one. This variable, myDog, is an object reference variable. Right now, it doesn't point to anything. If you don't assign it an object, its value is null. A null reference is like holding an empty leash.

Step 2: Instantiation (Getting the Dog) Next, you create the actual Dog object using the new keyword and the constructor.

myDog = new Dog("Buddy", "Golden Retriever", 5);

This is the magic moment.

Visualizing the two-step process of object creation.
  • The new keyword tells Java to allocate memory for a brand new Dog object.
  • Dog("Buddy", "Golden Retriever", 5) is the constructor call. It calls the Dog constructor, passing the values "Buddy", "Golden Retriever", and 5 as arguments.

Java then takes those arguments, jumps into the constructor's code, and runs it. The parameter dogName gets the value "Buddy", dogBreed gets "Golden Retriever", and so on. After the constructor finishes, the new object is created, and a reference (a memory address) to that object is returned and stored in our myDog variable. The leash is now attached to a real dog.

You can also do both steps in one line, which is what you'll see most often:

Dog myDog = new Dog("Buddy", "Golden Retriever", 5);

Overloaded Constructors: Multiple Ways to Order

What if you want to create a Dog object but don't know its age yet? A well-designed class can provide multiple constructors. This is called constructor overloading.

An overloaded constructor is just another constructor in the same class, but with a different signature. A constructor's signature is its name and the list of its parameter types.

public class Dog {
    String name;
    String breed;
    int age;

    // Constructor 1: Takes name, breed, and age
    public Dog(String dogName, String dogBreed, int dogAge) {
        name = dogName;
        breed = dogBreed;
        age = dogAge;
    }

    // Constructor 2 (Overloaded): Takes only name and breed
    public Dog(String dogName, String dogBreed) {
        name = dogName;
        breed = dogBreed;
        age = 0; // We'll just default the age to 0
    }
}

Now you have two ways to create a Dog:

// Uses the first constructor
Dog dog1 = new Dog("Lucy", "Beagle", 2);

// Uses the second, overloaded constructor
Dog dog2 = new Dog("Max", "German Shepherd"); // age will be 0

Java knows which constructor to call based on the arguments you provide. This is where most students slip up. You must match the number and type of arguments exactly.

new Dog("Rocky") would cause an error, because there is no constructor that takes only one String. new Dog("Poodle", "Fifi") would also cause an error, because the types are in the wrong order if a constructor expected (String, int).

When you call a constructor, the arguments you pass are copied into the constructor's parameters. This is called call by value. The constructor works with a copy, not the original variable.

Finally, remember that calling a constructor interrupts the flow of your program. If you have code in main, it executes line by line until it hits new Dog(). At that point, the program's focus jumps to the Dog class, runs the constructor code from top to bottom, and only when it's finished does it return to main to continue where it left off.

See it in action

python
Line 1
Output
Click Run to see the output.

        
Try these
    © Shrutam.ai

    Worked examples

    Let's walk through a few examples to make this crystal clear.

    Example 1: Creating a Book Object

    Problem: You have a Book class. Create an instance of a Book named theHobbit representing the book "The Hobbit" by "J.R.R. Tolkien", which has 310 pages.

    Here's the Book class:

    public class Book {
        String title;
        String author;
        int pageCount;
    
        // Constructor
        public Book(String bookTitle, String bookAuthor, int pages) {
            title = bookTitle;
            author = bookAuthor;
            pageCount = pages;
        }
    }

    Solution Walkthrough:

    1. 1
      Goal
      We need a Book object. This means we'll need the new keyword and a call to the Book constructor.
    2. 2
      Declare the variable
      First, we need a variable to hold our Book object. The type is Book and we can name it theHobbit. Book theHobbit;
    3. 3
      Identify the correct constructor
      The Book class has one constructor: Book(String, String, int). It needs a title (String), an author (String), and a page count (int), in that exact order.
    4. 4
      Prepare the arguments
      The problem gives us the arguments: "The Hobbit", "J.R.R. Tolkien", and 310. These match the types String, String, and int.
    5. 5
      Instantiate the object
      Now we use new to call the constructor with our arguments and assign the result to our variable. theHobbit = new Book("The Hobbit", "J.R.R. Tolkien", 310);
    6. 6
      Combine for clarity
      We can do this all in one line. Book theHobbit = new Book("The Hobbit", "J.R.R. Tolkien", 310);
    Example 2

    Using an Overloaded Constructor

    Problem: You have a Player class for a video game. Create two players: player1 is a new player named "Aaliyah" with a default score of 100. player2 is a returning player named "Carlos" with a known score of 2500.

    Here's the Player class:

    public class Player {
        String username;
        int score;
    
        // Constructor for returning players
        public Player(String name, int initialScore) {
            username = name;
            score = initialScore;
        }
    
        // Overloaded constructor for new players
        public Player(String name) {
            username = name;
            score = 100; // New players always start with 100 points
        }
    }

    Solution Walkthrough:

    1. 1
      Player 1 (Aaliyah)
      Aaliyah is a new player. The problem states new players get a default score. Looking at the Player class, the constructor Player(String name) is perfect for this. It only requires a name and handles setting the score to 100 internally.
      • Code
        Player player1 = new Player("Aaliyah");
      • Why
        We chose the constructor whose signature (String) matched the information we had for a new player.
    2. 2
      Player 2 (Carlos)
      Carlos is a returning player with a specific score. We have both his name and his score (2500). The constructor Player(String name, int initialScore) fits this perfectly.
      • Code
        Player player2 = new Player("Carlos", 2500);
      • Why
        We chose the constructor whose signature (String, int) matched the data we had.
    Common pitfalls when calling constructors.
    Constructor overloading logic.

    Try it yourself

    Time to try it on your own. Don't worry about getting it perfect, just focus on the process.

    Problem 1: You have a Coffee class for a shop in Seattle. The class has two overloaded constructors:

    • public Coffee(String type, int sizeOz)
    • public Coffee(String type) (this one defaults the size to 12 oz)

    Write two lines of code. First, declare and instantiate a Coffee object named morningMug that is a 16 oz "Latte". Second, declare and instantiate another Coffee object named afternoonCup that is a "Drip" coffee of the default size.

    Problem 2: A Rectangle class has a single constructor: public Rectangle(int width, int height). Your friend wrote the following line of code, but it has two errors. Rectangle myShape = Rectangle(50, 100);

    Identify both errors and write the corrected line of code.

    Fixing the Rectangle instantiation error.