CodeBlanks Logo Icon CodeBlanks

Class design

Design the library class skeleton.

Project: Library system

In this 5-lesson project you'll build a library system. Each lesson adds one piece, and by the final lesson you'll have a working program.

You'll use what you learned in previous groups: classes, constructors and inheritance. Throughout the project you'll define Library, Book, Member and Loan classes. In the first lesson you'll create the skeleton of the Library class: a name field, a constructor and a toString method.

The Library class skeleton

The first lesson defines the Library class. The class will have a name field, a constructor and a toString method. The constructor takes the name as a parameter and assigns it to the field.

Example skeleton: class Library { String name; Library(String n) { name = n; } public String toString() { return "Library: " + name; } }. This class forms the foundation for later lessons. Each lesson adds a new class on top. The constructor and toString provide a standard structure; book and member lists will be added later.

Practice Define the Library class

Define a class named Library. Add a String name field. Write a Library(String n) constructor that assigns name = n;. Add a public String toString() method returning "Library: " + name. In main create a Library instance and print it with println.

Starter code

Main.java
// Define the Library class
// Add field, constructor and toString
// Instantiate and print in main

Sample solution

Main.java
class Library {
    String name;
    Library(String n) {
        name = n;
    }
    public String toString() {
        return "Library: " + name;
    }
    public static void main(String[] args) {
        Library lib = new Library("Central");
        System.out.println(lib);
    }
}

Expected output

Library: Central

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which class is defined in the first lesson of the library system?

  • Library Correct answer
  • Book
  • Member
  • Loan

Explanation: The first lesson creates the skeleton of the Library class.

2 Complete the Library constructor

Question
class Library {
    String name;
    ____(String n) {
        name = n;
    }
}
Answer
class Library {
    String name;
    Library(String n) {
        name = n;
    }
}

Explanation: The constructor name must match the class name.

3 Match the Library parts

Term Meaning
String name Field
Library(String n) Constructor
toString String method
new Library(...) Instantiation

All lessons in Intermediate