Book.java: Instance Variables

Instance variables represent the state that an object keeps. In lecture, we discussed an MP3 player object that may keep state such as the remaining battery time, the collection of songs, and storage capacity. Here, the Book class has three instance variables: title, author, and rating. You can imagine that a more complex Book class could also store information such as the number of pages and year of publication.

The value of an instance variable is associated with a specific object instance. That is, we could create multiple Book objects with different titles, authors, and ratings.

At first glance, you may notice that Book's instance variables are prefixed with the keyword private. The private keyword tells Java that these variables can only be accessed within a Book object instance. More specifically, that means the following code is valid:

public class Book {
    ...
    public void setRatingTo42()
    {
        rating = 42;
    }
    ...
}

is valid. However, the following code is not:
public static void main(String[] args)
{
    Book b = ...
    b.rating = 42;
}