Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 2

Object Instantiation and Method Invocation

Recommended resources

In our previous lesson, you successfully designed the blueprint for a Riddle class, complete with its data fields and methods. Now, we'll take the crucial next step: bringing that blueprint to life. This lesson focuses on creating actual, usable objects from your class—a process called instantiation—and then interacting with them by calling their methods.

Mastering this step is fundamental. It's the bridge between abstract design and a running program that performs tasks. For your goal of building backend systems, you'll be constantly instantiating objects representing everything from user data to database connections and then orchestrating their interactions.

From Blueprint to Object: Instantiation

In Java, a class is just a template. To use it, you must create an instance, or an object, of that class. This is done using the new keyword, which allocates memory for the new object and calls the class's constructor to initialize it.

The general syntax is:
ClassName variableName = new ClassName(arguments);

Let's break this down:

  1. ClassName variableName: This declares a variable that will hold a reference to the object. Think of it not as the object itself, but as a "pointer" or an address that tells the Java Virtual Machine (JVM) where to find the object in memory.
  2. =: The assignment operator.
  3. new: The keyword that allocates memory for a new object.
  4. ClassName(arguments): This is the call to the constructor you defined in your class. The arguments you pass must match the parameters of the constructor.

For the Riddle class you created, instantiation would look like this:

Riddle riddle1 = new Riddle("What has an eye, but cannot see?", "A needle");

Here, riddle1 is a reference variable that points to a new Riddle object in memory. That object has been initialized with the question "What has an eye, but cannot see?" and the answer "A needle".


The main Method: Your Program's Entry Point

Where does this code go? In Java, the execution of a program starts in a special method: public static void main(String[] args). You've likely seen this many times in your DSA work. For now, think of it as the designated starting block for your application. We will place our object instantiation and method calls inside this main method.

It's common practice to have a main "runner" or "application" class that contains the main method, which then creates and uses objects from other classes you've defined (like your Riddle class).


Invoking Methods with the Dot Operator

Once you have an object, you need a way to access its members—specifically, its methods. This is done using the dot operator (.). The dot operator links the object reference to the member you want to access.

The syntax is straightforward:
variableName.methodName();

Continuing with our riddle1 object, you could call its methods like this:

// After creating the riddle1 object...
riddle1.printQuestion(); // This will execute the code inside the printQuestion() method.
riddle1.printAnswer();   // This will execute the code inside the printAnswer() method.

To solidify your understanding of object creation and method invocation, please review the following article from W3Schools. It provides a clear, step-by-step example.

Java Class Methods

This resource demonstrates how to create an object and call its methods. It also introduces the good practice of separating your main execution logic from your class definitions.

Please read the following sections: Begin at the section Access Methods With an Object. This shows the complete code for creating an object and calling its methods. Next, read the Example explained section, which breaks down each line of code. Pay special attention to points 7 and 8, which cover the new keyword and the dot operator. Finally, review the section Using Multiple Classes. This illustrates the standard practice of having one class (e.g., Main.java or Second.java) create and use objects from another class (e.g., Car.java).

The article you just read provides a great overview. Let's get a more formal definition of the dot operator itself from the following resource.

Java Dot Operator Simplifies Class Member Access

This article from Educba focuses specifically on the dot operator, its syntax, and its usage for accessing different class members.

Read the following parts: The Introduction for a formal definition. The section Usage of Dot Operator, which explains how it connects an object to its members. Focus on the subsection To invoke a method. Study the full example under the heading Accessing Methods and Variables. Notice how this Book class is a POJO, similar to the pattern we discussed in the last lesson, and see how its methods are called on the myBook object.


State and Behavior in Action

An object encapsulates both state (the data in its fields) and behavior (the actions in its methods). When you invoke a method on an object, that method operates on the specific state of that instance.

This is a powerful concept. You can create many objects from the same class, and each one will be independent, with its own unique state. Calling the same method on different objects can produce different results.

The following video provides an excellent practical demonstration of this. The instructor creates Student objects, each with a different GPA (its state), and then calls a method isOnHonorRoll() (its behavior) to see if that specific student qualifies.

Object & Instance Methods | Java | Tutorial 30

This Giraffe Academy tutorial is a great walkthrough of creating objects and calling instance methods that depend on the object's state.

Please watch the following segments: Creating a student object. See how the new keyword is used with the constructor to pass initial values. Defining an instance method. The instructor creates the isOnHonorRoll method. Notice how it uses this.gpa to access the GPA of the specific student object it's called on. Calling the instance method. Here, you'll see the dot notation in action (myStudent.isOnHonorRoll()) and how the result changes based on the GPA passed to the constructor.

The image below shows a simple instantiation and field assignment within an IntelliJ IDEA environment, which is very similar to what you'll be doing in your own projects. The line Phone phone1 = new Phone(); creates the object, and the subsequent lines use the dot operator to access and set its fields.

This code snippet shows the instantiation of a `Phone` object using `new Phone()`. The dot operator is then used to access and assign values to the public fields of the `phone1` object.

While this image shows direct access to fields (e.g., phone1.os = "Android"), in the next lesson we'll reinforce why using methods (like phone1.setOs("Android")) is the preferred approach for maintaining encapsulation. For now, focus on the new keyword and the dot operator syntax.


Your Turn: Bring Your Riddles to Life

Now it's time to put theory into practice. You will create a separate Main class to run your program. From there, you will instantiate and interact with the Riddle class you built in the previous lesson.

Instructions:

  1. In your Java project, create a new class file named Main.java.
  2. Inside this class, create the public static void main(String[] args) method.
  3. Inside the main method, do the following:
    • Instantiate at least two different Riddle objects. Give each one a unique question and answer when you create it.
    • For the first riddle object, call its printQuestion() method, followed by its printAnswer() method.
    • Add a blank line (System.out.println();) for spacing.
    • For the second riddle object, do the same: call printQuestion() and then printAnswer().

When you run your Main.java file, your console output should look something like this:

What has to be broken before you can use it?
An egg

I’m tall when I’m young, and I’m short when I’m old. What am I?
A candle

This exercise will confirm that you can successfully create and use objects from a class blueprint.


Key Takeaways

  • Objects are created from a class using the new keyword, which allocates memory and calls a constructor.
  • A variable of a class type holds a reference (memory address) to an object, not the object itself.
  • The public static void main(String[] args) method is the entry point for a Java application.
  • The dot operator (.) is used to access an object's members, most importantly to invoke its methods (object.method()).
  • Each object created from a class is a distinct instance with its own state, allowing methods to behave differently depending on which object they are called on.

What's Next?

You can now create class blueprints and bring them to life as objects. However, in our examples, we've sometimes seen direct access to an object's fields (like phone1.os = ...). This can lead to unreliable and hard-to-maintain code.

In the next lesson, we will formally dive into access modifiers (public, private, protected, default). You will learn how to properly enforce encapsulation, protecting an object's data and exposing only controlled, intentional behaviors. This is a pillar of object-oriented design and is essential for building the kind of robust backend services you're aiming for.