Designing and Creating Objects in JavaScript

Computer Programmer
PeopleImages/Getty Images
01
of 07

Introduction

Before you read this step-by-step guide you might want to cast your eye over the introduction to object-oriented programming. The Java code contained in the following steps matches the example of a Book object used in the theory of that article.​

By the end of this guide you will have learned how to:

  • design an object
  • store data in an object
  • manipulate data in an object
  • create a new instance of an object

The Class File

If you're new to objects you will most likely be used to created Java programs using only one file – a Java main class file. It's the class that has the main method defined for the starting point of a Java program.

The class definition in the next step needs to be saved in a separate file. It follows the same naming guidelines as you have been using for the main class file (i.e., the name of the file must match the name of the class with the filename extension of .java). For example, as we are making a Book class the following class declaration should be saved in a file called "Book.java".

02
of 07

The Class Declaration

The data an object holds and how it manipulates that data is specified through the creation of a class. For example, below is a very basic definition of a class for a Book object:

public class Book {


}

It's worth taking a moment to break down the above class declaration. The first line contains the two Java keywords "public" and "class":

  • The public keyword is known as an access modifier. It controls what parts of your Java program can access your class. In fact, for top-level classes (i.e., classes not contained within another class), like our book object, they have to be public accessible.
  • The class keyword is used to declare that everything within the curly brackets is part of our class definition. It's also followed directly by the name of the class.
03
of 07

Fields

Fields are used to store the data for the object and combined they make up the state of an object. As we're making a Book object it would make sense for it to hold data about the book's title, author, and publisher:

public class Book {

   //fields
   private String title;
   private String author;
   private String publisher;
}

Fields are just normal variables with one important restriction – they must use the access modifier "private". The private keyword means that theses variables can only be accessed from inside the class that defines them.

Note: this restriction is not enforced by the Java compiler. You could make a public variable in your class definition and the Java language won't complain about it. However, you will be breaking one of the fundamental principles of object-oriented programming – data encapsulation. The state of your objects must only be accessed through their behaviors. Or to put it in practical terms, your class fields must only be accessed through your class methods. It's up to you to enforce data encapsulation on the objects you create.

04
of 07

The Constructor Method

Most classes have a constructor method. It's the method that gets called when the object is first created and can be used to set up its initial state:

 public class Book {

   //fields
   private String title;
   private String author;
   private String publisher;

   //constructor method
   public Book(String bookTitle, String authorName, String publisherName)
   {
     //populate the fields
     title = bookTitle;
     author = authorName;
     publisher = publisherName;
   }
}

The constructor method uses the same name as the class (i.e., Book) and needs to be publicly accessible. It takes the values of the variables that are passed into it and sets the values of the class fields; thereby setting the object to it's initial state.

05
of 07

Adding Methods

Behaviors are the actions an object can perform and are written as methods. At the moment we have a class that can be initialized but doesn't do much else. Let's add a method called "displayBookData" that will display the current data held in the object:

 public class Book {

   //fields
   private String title;
   private String author;
   private String publisher;

   //constructor method
   public Book(String bookTitle, String authorName, String publisherName)
   {
     //populate the fields
     title = bookTitle;
     author = authorName;
     publisher = publisherName;
   }

   public void displayBookData()
   {
     System.out.println("Title: " + title);
     System.out.println("Author: " + author);
     System.out.println("Publisher: " + publisher);
   }
}

All the displayBookData method does is print out each of the class fields to the screen.

We could add as many methods and fields as we desire but for now let's consider the Book class as complete. It has three fields to hold data about a book, it can be initialized and it can display the data it contains.

06
of 07

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

07
of 07

Multiple Objects

Now we can begin to see the power of objects. I could extend the program:

 public class BookTracker {

   public static void main(String[] args) {

     Book firstBook = new Book("Horton Hears A Who!","Dr. Seuss","Random House");
     Book secondBook = new Book("The Cat In The Hat","Dr. Seuss","Random House");
     Book anotherBook = new Book("The Maltese Falcon","Dashiell Hammett","Orion");
     firstBook.displayBookData();
     anotherBook.displayBookData();
     secondBook.displayBookData();
   }
}

From writing one class definition we now have the ability to create as many Book objects as we please!

Format
mla apa chicago
Your Citation
Leahy, Paul. "Designing and Creating Objects in JavaScript." ThoughtCo, Aug. 27, 2020, thoughtco.com/designing-and-creating-objects-2034342. Leahy, Paul. (2020, August 27). Designing and Creating Objects in JavaScript. Retrieved from https://www.thoughtco.com/designing-and-creating-objects-2034342 Leahy, Paul. "Designing and Creating Objects in JavaScript." ThoughtCo. https://www.thoughtco.com/designing-and-creating-objects-2034342 (accessed March 28, 2024).