Originally posted by luk Hann:
[B]Hi, I am new to write code and not feeling confident about the code I wrote. For the following programming excercise:
Design a Java class to represents a book which may be borrowed from a public library.
Some behaviors for the class are:
int getId( ) - gets the acquisition number of the book (unique for each title)
setBorrowed(boolean) - sets or clears the borrowed status of the book.// Do I need to initialize the setBorrowed "false"?
The acquisition number of this book is automatically generated by the constructor. The acquisition numbers are integers starting with 1 and increase by 1 for each new title generated.// How to express this in the code?
I tried to write the following code but not sure whether I did correct with the above two questions I commented. Please let me know if you think something is wrong with the code. Thanks.
[/B]
public class Book1 {
private static int nextId = 1;
private int id;
private boolean bBorrowed; // no need to intialize
public Book1() { // constructor
id = nextId++; // this should be in the constructor
}
public int getId () {
return id;
}
public void setBorrowed (boolean b) {
bBorrowed = b; // set the member variable
}
// test the class
public static void main(String[] args){
Book1 b1 = new Book1();
System.out.println("Book: " + b1.getId());
System.out.println("Borrowed: " + b1.bBorrowed);
// now set the Borrowed status
b1.setBorrowed(true);
System.out.println("Borrowed: " + b1.bBorrowed);
// try one more book
b1 = new Book1();
System.out.println("Book: " + b1.getId());
System.out.println("Borrowed: " + b1.bBorrowed);
}
}