1. Home
  2. Computing & Technology
  3. Java

Designing and Creating Objects

By Paul Leahy, About.com

5 of 7

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.

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. Adding Methods

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

All rights reserved.