Skip to content
ExamSpine

Answer it

P2 b134 library static count

5 marksYou mark it yourself against the marking points

The school library's Book class now also counts how many books have been created. Here it is in Python and in Java, with code that uses it. In Java the last part runs inside a main method.

class Book:
    count = 0

    def __init__(self, title, copies):
        self.title = title
        self.__available = copies
        Book.count += 1

    def get_available(self):
        return self.__available

    def borrow(self):
        if self.__available > 0:
            self.__available -= 1
            return True
        return False

b1 = Book("Dune", 1)
b2 = Book("Emma", 2)
print(b1.borrow())
print(b1.borrow())
print(b2.borrow())
print(b2.get_available())
print(Book.count)
public class Book {
    private static int count = 0;
    private String title;
    private int available;

    public Book(String title, int copies) {
        this.title = title;
        this.available = copies;
        count++;
    }

    public int getAvailable() {
        return available;
    }

    public boolean borrow() {
        if (available > 0) {
            available--;
            return true;
        }
        return false;
    }

    public static int getCount() {
        return count;
    }
}

// in main
Book b1 = new Book("Dune", 1);
Book b2 = new Book("Emma", 2);
System.out.println(b1.borrow());
System.out.println(b1.borrow());
System.out.println(b2.borrow());
System.out.println(b2.getAvailable());
System.out.println(Book.getCount());

(a) State the five lines of output, in order. [3]

(b) Explain why the last line of output is 2 and not 1. [2]

[5]