Home > Net >  How to set field value of class A using an object of class B? What type of relationship should be be
How to set field value of class A using an object of class B? What type of relationship should be be

Time:10-03

I have a Library class which has a librarian and list of book and Librarian class which has an id and addBook method. The librarian class can add books in the library. What will be the correct way to do this?

public class Library 
{
 private Librarian librarian;
 private List<Book> books;
}

public class Librarian
{
 private int id;
 public boolean addBook(Book b);
}

CodePudding user response:

It might be better to have the addBook method as part of the library class. Then you can use a library instance to do something as simple as

 public boolean addBook(Book b) {
    books.add(b);
 }

In this case, the librarian would be the user of the program. But you will probably need a way to get the book from the list. And you may want to search for various fields (key word, title, etc) which would be more detailed and return one or more matching books. You don't need to return a boolean unless you want to determine if the book has already been added (false) or is a new entry (true).

CodePudding user response:

can a librarian be a librarian for more libraries? If only to one, then I would give the Librarian class a Library object and initialise it in the constructor

public class Librarian
{
 private int id;
 private final Library library;
 public boolean addBook(Book b);

 public Librarian(final Library library) {
  this.library = library;
 }
}

add getters.

then you can add a book like this

librarian.getLibrary().addBook(book);
  • Related