Java
Member management
Register members with Member.
Member management
The third lesson defines the Member class. Each member has a name and an ID number. The Member class represents people who register at the library.
Example: class Member { String name; int id; Member(String n, int i) { name = n; id = i; } }. This class is also added alongside Library and Book. A toString method shows the member readably: name + " (" + id + ")". The member ID should be unique; the library assigns it during registration. Later, loan operations will use these members.
Three classes together
You now have three classes: Library, Book and Member. Each is defined with its own fields and constructor. By putting the main method in the most recently added class, you can test the instance.
Example: In Member's main method, a member is created with new Member("Alex", 101) and printed. The other classes stay unchanged. This structure shows the project growing step by step; each lesson adds a class and preserves the previous code. The next lesson will define the loan flow that links these classes.
Exercise Add the Member class
Add a Member class to the file. Write String name and int id fields. Add a Member(String n, int i) constructor; assign both fields. Add a public String toString() method returning name + " (" + id + ")". Put main inside Member; create a Member instance and print it.
Show example solution
class Library {
String name;
Library(String n) {
name = n;
}
public String toString() {
return "Library: " + name;
}
}
class Book {
String title;
String author;
Book(String t, String a) {
title = t;
author = a;
}
public String toString() {
return title + " - " + author;
}
}
class Member {
String name;
int id;
Member(String n, int i) {
name = n;
id = i;
}
public String toString() {
return name + " (" + id + ")";
}
public static void main(String[] args) {
Member m = new Member("Alex", 101);
System.out.println(m);
}
}
Test yourself
-
What type should the id field of Member be?
Show answer
int — The id is an integer; int is suitable.
-
Complete the Member constructor
class Member {
String name;
int id;
____(String n, int i) {
name = n;
id = i;
}
}
Show answer
class Member {
String name;
int id;
Member(String n, int i) {
name = n;
id = i;
}
}
-
Match the Member parts
- String name
- Name field
- int id
- ID field
- Member(String n, int i)
- Constructor
- name + id
- toString body
Next lesson: Borrow flow