Java Reference
In-Depth Information
Book(String t, int r) {
title = t;
releaseYear = r;
}
void sell(int nrCopies) {
copiesSold += nrCopies;
}
int nrCopiesSold() {
return copiesSold;
}
}
If you now want to create an actual program that can be executed, the simplest way to do so is by
creating a main method within this class, like so:
class Book {
final String title;
final int releaseYear;
int copiesSold;
Book(String t, int r) {
title = t;
releaseYear = r;
}
void sell(int nrCopies) {
copiesSold += nrCopies;
}
int nrCopiesSold() {
return copiesSold;
}
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);
}
}
In general, however, it is not good practice to mix a main method with a class definition relating to
a real‐world concept. As such, it is better to create a separate “controller” class to separate program
logic from class concepts, like so:
// File Book.java:
class Book {
final String title;
final int releaseYear;
int copiesSold;
Search WWH ::




Custom Search