简体   繁体   中英

How to set field value of class A using an object of class B? What type of relationship should be between the classes to do so?

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);
}

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).

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);

As librarian add book into library and library has all books, so it looks better to place implementation of method addBook in library class.

So code would like this:

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

    public bool AddBook(Book book)
    {
        books.Add(book);
        return true;
    }
}

And Libranian can add a book into library like this:

public class Librarian
{
    private int id;
    private Library library;

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


    public bool AddBook(Book b)
    {
        return library.AddBook(b);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM