Search code examples
javacompositecomposite-component

Get Author name from composite class Book


So, I'm new with Object-oriented programming. I have written a code to connect the composite and component class, I need to include at least one method that allows the composite class to communicate with the component class in order to compute some value. But my Book class is not showing the author's name.

This is my code:

public class Author{

private String name;
private String yearOfBirth;  

    public Author ()
    this.name = null;
    this.yearOfBirth = null;   
    }

    public Author (String aName)
    {
       this.name = aName;
       this.yearOfBirth = null;

   }
    public Author(String aName, String     aYear)
    {
  this.name = aName;
  this.yearOfBirth = aYear;
  }

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

 public void setYearOfBirth(String aYear)
  {
  this.yearOfBirth = aYear;
 }

    public String getName()
    {
     return this.name;
     }

    public String getYearOfBirth()
     {
      return this.yearOfBirth;
    }  

public String toString()
{
   return this.name + "(Born " + this.yearOfBirth + ")";
}

BOOK CLASS

public class Book
{

 private String title;
 private String yearPublished;
 private Author author;


 public Book(String aTitle, String aYear,Author theAuthor)
  {
    this.title = aTitle;
    this.yearPublished = aYear;
    this.author = theAuthor;
   }


 public Book(String aTitle)
 {
   this.title = aTitle;
   this.yearPublished = null;
   this.author = new Author();
 }

 public void setAuthorName(String aName)
  {
      this.author.setName(aName);
 } 

  public void setYearPublished(String aYear)
  {
     this.yearPublished = aYear;
    }

     public String getTitle()
  {
     return this.title;   
  }

  public String getYearPublished()
   {
    if (this.yearPublished == null)
    {
       return "Unknown";
     }

     return this.yearPublished;
      }

   public String getAuthorName()
   {
     return this.author.getName();
    }

    public boolean isBorn()
    {
         return(Integer.parseInt
   (this.author.getYearOfBirth()) < 1900);
  }

public String toString()
  {

 {
    return "Title: " + this.title + ", Author: " + this.author.getName() + ", yearPublished: " + this.yearPublished+ ".";          
 } 

So when I try and get the author name by doing something like: Book hp = new Book ("Harry Potter","JK Rowling","2000"); it says in the display pane

Compilation failed (20/01/2020 15:02:12)
Error: line 1 - no suitable constructor found for Book(java.lang.String,java.lang.String,java.lang.String)

As you can see, the program does not print the name of the author.

I appreciate all the help!


Solution

  • Because your builder's call is no good.

    Book class is waiting to get a title like String , one year of String type

    and an Author type author

    Example Book book =new Book("test", "2020", new Author("MyAuthor"));