Java Reference
In-Depth Information
Note If you were thinking, “Wouldn't it be a good idea to abstract authors
away into a separate class, say, Author?”, you would be absolutely right,
although it depends on the complexity you foresee your program having
to deal with. Can you imagine keeping author information nicely separated
with authors having their own data (first name, last name, and birth date) and
behaviors? Then yes, it makes sense to create an Author class. If you are plan-
ning on keeping a simple string to represent author information for topics (like
you are doing here), the simple solution is fine.
To paraphrase the famous quote from Einstein, “Everything should be made as
simple as possible, but no simpler.”
Now, you have already seen how to create some Book objects, that is, some topics. For example, you
might write a piece of code doing something like the following:
Book book1 = new Book();
book1.title = "Beginning Java";
book1.authors = new String[]{
"Bart Baesens",
"Aimee Backiel",
"Seppe vanden Broucke"
};
Book book2 = new Book();
book2.title = "Catcher in the Rye";
book2.authors = new String[]{"J. D. Salinger"};
This code creates two book objects— book1 and book2 —and sets their title and author variables.
As you can observe, each book object keeps its own copy of the title and author variables, which
can be accessed and modified independently.
That is all you need to know to get the idea about what instance variables are all about. They are
basically just a part of the class blueprint, and get instantiated for each object you define belonging
to that class.
As a reminder, however, recall that you can define multiple variables of the same type by separating
them with commas, like so:
int a, b, c;
In fact, this not only works for instance variables, but works for any variable you define no matter
where and no matter of which type (it does not have to be a primitive type). For example, the code
sample to create the two topics could also be rewritten like so:
Book book1, book2; // Define two empty Book objects
book1 = new Book(); // Set first book
book1.title = "Beginning Java";
book1.authors = new String[]{
Search WWH ::




Custom Search