Bài tập Java OOP: tạo lớp sách và tác giả | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create an Author class and a Book class with the information as in the following class diagram:

Explanation:

Author class

  • This class is used for storing information about the author of the book.
  • name, email attributes describe name and address of the author.
  • Author(name: String, email: String) is the parameter constructor which is used for initializing values to the corresponding attributes.
  • setName(), getName(), setEmail(), getEmail() are setters and getter.

Book class

  • This class is used for storing information about books. 
  • name, price, authors are attributes storing name, price and author of the book respectively.
  • Book(name: String, authors: Author[], price: double) is the parameter constructor which is used for initializing values to the corresponding attributes.
  • setName(), getName(), setPrice(), getPrice() are setters and getters.
  • getAuthorNames() method returns the author names of the book in the following format "authorName1, authorName2, ..., authorNameN".

A program to test the above classes:

public class Entry {
	public static void main(String[] args) {
		Author[] authors = new Author[3];
		authors[0] = new Author("Viet", "[email protected]");
		authors[1] = new Author("Tuan", "[email protected]");
		authors[2] = new Author("Kien", "[email protected]");
		
		Book book1 = new Book("C++ for Beginners", authors, 210000);
		System.out.println(book1.getAuthorNames());
	}
}

When the above code is compiled and executed, it produces the following result:

Viet, Tuan, Kien

Instruction

Code sample:

File Author.java

public class Author {
	private String name;
	private String email;

	public Author(String name, String email) {
		this.name = name;
		this.email = email;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}

File Book.java

public class Book {
	private String name;
	private double price;
	private Author[] authors;

	public Book(String name, Author[] authors, double price) {
		this.name = name;
		this.price = price;
		this.authors = authors;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public String getAuthorNames() {
		String authorNames = "";
		for (int i = 0; i < authors.length - 1; i++) {
			authorNames += authors[i].getName() + ", ";
		}
		authorNames += authors[authors.length - 1].getName();
		return authorNames;
	}
}