1. Home
  2. Computing & Technology
  3. Java

Designing and Creating Objects

By , About.com Guide

3 of 7

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.

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. Fields

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

All rights reserved.