1. Home
  2. Computing & Technology
  3. Java

Designing and Creating Objects

By Paul Leahy, About.com

4 of 7

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.

Explore Java
About.com Special Features

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

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Java
  4. Java Syntax
  5. Working With Objects
  6. The Constructor Method

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

All rights reserved.