Java Reference
In-Depth Information
Book(String t, int r) {
title = t;
releaseYear = r;
}
void sell(int nrCopies) {
copiesSold += nrCopies;
}
int nrCopiesSold() {
return copiesSold;
}
}
// File Program.java:
class Program {
public static void main(String[] args) {
Book firstBook = new Book("First Book", 2004);
Book secondBook = new Book("Another Book", 2014);
firstBook.sell(200);
System.out.println("Number of copies sold of first book is now: "
+firstBook);
System.out.println("Title of the second book is: "+secondBook.title);
}
}
Some developers like to supply main methods in their class definitions in larger programs as a quick
way to test if the class is working correctly, without having to run the complete program and go
through a series of steps. This is fine, so long as you keep these “test” main is small and short, for
testing purposes only, and remember that there exist better ways to perform thorough code tests.
This remark does illustrate another aspect, though, namely the fact that a Java project can contain
multiple main methods. In fact, it's possible to provide a main method in every class you define. So
how does Eclipse or Java know how to execute which one? To figure this out, you'll return to the
very first example context you saw at the beginning of this chapter: the course administration pro-
gram. The following Try It Out will guide you from beginning to end to re‐create the course admin-
istration example, using all of the knowledge you've gained so far.
Course and Student administration revisited 
try it out
Let's revisit the course and student administration example you saw earlier, now applying all of the
knowledge you've gained so far.
1.
It's best to create a new project in Eclipse. Remember you can do so by navigating to File New
and then selecting Java Project in Eclipse. A dialog window will open asking you to fill in a project
name, such as CourseAdministrationDoneWell . You can then press Finish to create the project.
2.
Create the Course.java class by right‐clicking the src folder in the package explorer in Eclipse
and then selecting New Class. Define this class as follows:
import java.util.HashSet;
class Course {
static int nextId = 0;
Search WWH ::




Custom Search