1. Home
  2. Computing & Technology
  3. Java

Designing and Creating Objects

By , About.com Guide

6 of 7

Creating an Instance of an Object

To create an instance of the Book object we need a place to create it from. Make a new Java main class as shown below (save it as BookTracker.java in the same directory as your Book.java file):

public class BookTracker {

   public static void main(String[] args) {

   }
}

To create an instance of the Book object we use the "new" keyword as follows:

public class BookTracker {

   public static void main(String[] args) {

     Book firstBook = new Book("Horton Hears A Who!","Dr. Seuss","Random House");
   }
}

On the left hand side of the equals sign is the object declaration. It's saying I want to make a Book object and call it "firstBook". On the right hand side of the equals sign is the creation of a new instance of a Book object. What it does is go to the Book class definition and run the code inside the constructor method. So, the new instance of the Book object will be created with the title, author and publisher fields set to "Horton Hears A Who!", "Dr Suess" and "Random House" respectively. Finally, the equals sign sets our new firstBook object to be the new instance of the Book class.

Now let's display the data in firstBook to prove that we really did create a new Book object. All we have to do is call the object's displayBookData method:

public class BookTracker {

   public static void main(String[] args) {

     Book firstBook = new Book("Horton Hears A Who!","Dr. Seuss","Random House");
     firstBook.displayBookData();
   }
}

The result is:
Title: Horton Hears A Who!
Author: Dr. Seuss
Publisher: Random House

Explore Java
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Java
  4. Java Syntax
  5. Working With Objects
  6. Creating an Instance of an Object

©2009 About.com, a part of The New York Times Company.

All rights reserved.