Object Creation and Storage (Instantiation)
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];
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:
- A constructor always has the exact same name as the class.
- 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.
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.
- The
newkeyword tells Java to allocate memory for a brand newDogobject. Dog("Buddy", "Golden Retriever", 5)is the constructor call. It calls theDogconstructor, passing the values"Buddy","Golden Retriever", and5as 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
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:
- 1GoalWe need a
Bookobject. This means we'll need thenewkeyword and a call to theBookconstructor. - 2Declare the variableFirst, we need a variable to hold our
Bookobject. The type isBookand we can name ittheHobbit.Book theHobbit; - 3Identify the correct constructorThe
Bookclass has one constructor:Book(String, String, int). It needs a title (String), an author (String), and a page count (int), in that exact order. - 4Prepare the argumentsThe problem gives us the arguments:
"The Hobbit","J.R.R. Tolkien", and310. These match the typesString,String, andint. - 5Instantiate the objectNow we use
newto call the constructor with our arguments and assign the result to our variable.theHobbit = new Book("The Hobbit", "J.R.R. Tolkien", 310); - 6Combine for clarityWe can do this all in one line.
Book theHobbit = new Book("The Hobbit", "J.R.R. Tolkien", 310);
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:
- 1Player 1 (Aaliyah)Aaliyah is a new player. The problem states new players get a default score. Looking at the
Playerclass, the constructorPlayer(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"); - WhyWe chose the constructor whose signature
(String)matched the information we had for a new player.
- Code
- 2Player 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); - WhyWe chose the constructor whose signature
(String, int)matched the data we had.
- Code
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.
Practice — 8 questions
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.
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;
}
}
- 1.13.A: Identify, using its signature, the correct constructor being called.
- 1.13.B: Develop code to declare variables of the correct types to hold object references.
- 1.13.C: Develop code to create an object by calling a constructor.
- 1.13.A.1
- A class contains constructors that are called to create objects. They have the same name as the class.
- 1.13.A.2
- A constructor signature consists of the constructor's name, which is the same as the class name, and the ordered list of parameter types. The parameter list, in the header of a constructor, lists the types of the values that are passed and their variable names.
- 1.13.A.3
- Constructors are said to be overloaded when there are multiple constructors with different signatures.
- 1.13.B.1
- A variable of a reference type holds an object reference or, if there is no object, null.
- 1.13.C.1
- An object is typically created using the keyword new followed by a call to one of the class's constructors.
- 1.13.C.2
- Parameters allow constructors to accept values to establish the initial values of the attributes of the object.
- 1.13.C.3
- A constructor argument is a value that is passed into a constructor when the constructor is called. The arguments passed to a constructor must be compatible in order and number with the types identified in the parameter list in the constructor signature. When calling constructors, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments.
- 1.13.C.4
- A constructor call interrupts the sequential execution of statements, causing the program to first execute the statements in the constructor before continuing. Once the last statement in the constructor has been executed, the flow of control is returned to the point immediately following where the constructor was called.
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];
Read what Saavi narrates
(gentle, warm intro music fades)
Hi everyone, it's Saavi. Welcome to Shrutam.
Have you ever ordered a custom drink at a coffee shop? You walk up and say, "I'd like a large iced coffee with oat milk and one pump of vanilla." That list on the wall... that's the menu, the blueprint. But the drink the barista hands you... that's your specific, real object.
That's exactly what we're talking about today in Java: taking a class, which is like the menu, and using it to create an actual object, like your custom coffee. This process is called instantiation, and it's the moment our code brings things to life.
Let's look at a quick example. Imagine we have a class called `Book`. The class definition says every book needs a title, an author, and a page count. To create a specific book, we use a special method called a constructor.
Let's say the constructor looks like this: `Book(String title, String author, int pages)`.
To create "The Hobbit", we would write: `Book theHobbit = new Book("The Hobbit", "J.R.R. Tolkien", 310);`
Let's break that down. The `new` keyword is the magic word. It tells Java, "Hey, make a new thing!" Then, we call the `Book` constructor and pass in our specific details—the title, the author, and the page count—as arguments. Java uses these arguments to build the object, and then it hands us back a reference to that new object, which we store in our `theHobbit` variable.
One of the most common mistakes I see is students forgetting that `new` keyword. They'll write `Book theHobbit = Book(...)`. That won't work. You have to use `new` to signal that you're making something from scratch. Think of it as telling the barista "I'd like a *new* coffee," not just shouting ingredients at them.
You're building the fundamental skills of a programmer right now. It might feel like a lot of rules, but with practice, it becomes second nature. You've got this.
(outro music begins)
This looks like a regular method call. Constructors must be invoked with the `new` keyword to tell Java to allocate memory for a new object.
Always use `new` when creating an object.
// Correct
Car myCar = new Car("Toyota", "Camry");
The constructor expects a `String` first, then an `int`. You provided an `int`, then a `String`. The types and their order must match the constructor's signature exactly.
Ensure your arguments match the constructor's parameter list in both number and type.
// Correct
Student s1 = new Student("Priya", 11);
`Dog myDog;` only creates a reference variable (the "leash"). It does not create a `Dog` object. The variable `myDog` holds the value `null`. You can't call methods on `null`.
You must instantiate the object with `new` before you can use it.
// Correct
Dog myDog = new Dog();
myDog.bark();
Constructors are only used once, at the moment of creation (with `new`). You cannot call them like regular methods to "re-initialize" an object. You would use a setter method for that (e.g., `p1.setScore(500);`).
Use constructors only with the `new` keyword. To change an object's state after it's created, call its methods.
// Wrong
Player p1 = new Player("Marcus");
p1.Player("Marcus", 500); // Error!
Java provides a "free" no-argument constructor *only if you don't write any constructors yourself*. The moment you write even one constructor, that free one disappears.
If you need a no-argument constructor in addition to others, you must write it explicitly.
public class Item {
String name;
// You must add this yourself
public Item() { name = "default"; }
public Item(String n) { name = n; }
}